我有一個字典,其中的值是一個字典串列:
{ 'client1':
[
{ 'id': 123, 'name': 'test1', 'number': 777 },
{ 'id': 321, 'name': 'test2', 'number': 888 },
{ 'id': 456, 'name': 'test3', 'number': 999 }
],
...
}
并且有很多條目鍵clientX。
現在,為了使用 eg 獲取條目name == test2,我遍歷串列并檢查name值,如下所示:
for l in d['client']:
if 'test2' in l['name']:
# process the entry
...
有沒有更短/緊湊的方法來進行這樣的查找?
uj5u.com熱心網友回復:
您可以使用串列理解:
if "test2" in [l["name"] for l in d["client"]]:
# process the entry
這會生成完整的名稱串列供您進行比較,這確實將您的代碼縮短了一行,同時也使其更難閱讀。
uj5u.com熱心網友回復:
我想你想要這樣的東西。
for v in d.values():
item = next((x for x in v if x["name"] == "test2"), None)
item and print("found: ", item)
正如你在python2 中那樣說明的item and print("found: ", item)
if item:
print "found: ", item
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/346025.html
標籤:Python python-2.7 字典
