简体   繁体   中英

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

I have a list of dictionaries, which all have the same keys. I have a specific value of one key and want to access/print the dictionary, which contains this specific value. I couldn't think of any way, other than looping around the whole list, checking the corresponding value of the key and printing it out using if statement, that is if the given value matched the key.

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

This does not really seem the most efficient way to handle the task. What would be a better solution?

Some options:

1- Use the loop like you do here, although this could be written simpler without the continue.

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

2- Use a generator expression and next

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

3- Convert the list of dictionaries into a dictionary of dictionaries. This is a good option if you have to do this operation many times and there is only one value for each account_key

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

4- Same as above, but if there are multiple values for the same key, you can use a dict of lists of dicts.

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

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

You can use a comprehension (iterator) to get the subset of dictionaries that match your criteria. In any case this will be a sequential search process.

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM