簡體   English   中英

如何使用我想要獲取的字典的一個鍵/值對從字典列表中訪問字典

[英]How to access the dictionary from a list of dictionaries using one key/value pair of the dictionary that I want to fetch

我有一個字典列表,它們都有相同的鍵。 我有一個鍵的特定值,想訪問/打印包含此特定值的字典。 除了遍歷整個列表,檢查鍵的相應值並使用if語句打印出來之外,我想不出任何方法,即給定的值是否與鍵匹配。

for enrollment in enrollments:
    if enrollment['account_key'] == a:
        print(enrollment)
    else:
        continue

這似乎並不是處理任務的最有效方式。 什么是更好的解決方案?

一些選項:

1- 像這里一樣使用循環,盡管如果沒有 continue,這可以寫得更簡單。

for enrollment in enrollments:
    if enrollment['account_key'] == a:
        print(enrollment)

2-使用生成器表達式和next

enrollment = next(e for e in enrollments if e['account_key'] == a)
print(enrollment)

3- 將字典列表轉換為字典字典。 如果您必須多次執行此操作並且每個account_key只有一個值,這是一個不錯的選擇

accounts = {
    enrollment['account_key']: enrollment
    for enrollment in enrollments
}
print(accounts[a])

4- 同上,但如果同一個鍵有多個值,您可以使用字典列表。

accounts = defaultdict(list)
for enrollment in enrollments:
    accounts[enrollment['account_key']].append(enrollment)

for enrollment in accounts[a]:
    print(enrollment)

您可以使用理解(迭代器)來獲取符合您的條件的字典子集。 無論如何,這將是一個順序搜索過程。

enrolments = [ {'account_key':1, 'other':99},
               {'account_key':2, 'other':98},
               {'account_key':1, 'other':97},
               {'account_key':1, 'other':96},
               {'account_key':3, 'other':95} ]

a = 1
found = (d for d in enrolments if d['account_key']==a)
print(*found,sep="\n")

{'account_key': 1, 'other': 99}
{'account_key': 1, 'other': 97}
{'account_key': 1, 'other': 96}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM