简体   繁体   中英

Is there a more pythonic/compact way to create this dictionary?

I have a dictionary of lists of dictionaries that looks like this:

original_dict = {
    1: [{'name': 'Sam'}, {'name': 'Mahmoud'}, {'name': 'Xiao'}], 
    2: [{'name': 'Olufemi'}, {'name': 'Kim'}, {'name': 'Rafael'}]
}

I know that the names in the lists in this dictionary are all unique. IE: the same name will not appear multiple times in this structure. I want to compile a dictionary of all sub-dictionaries, keyed by their names. I want the result to look like this:

result_dict = {
    'Sam': {'name': 'Sam'}, 
    'Mahmoud': {'name': 'Mahmoud'}, 
    'Xiao': {'name': 'Xiao'},
    'Olufemi': {'name': 'Olufemi'}, 
    'Kim': {'name': 'Kim'}, 
    'Rafael': {'name': 'Rafael'}
}

So far my solution looks like this:

result_dict = {}
for list_of_dicts in original_dict.values:
    for curr_dict in list_of_dicts:
        result_dict[curr_dict['name']] = curr_dict

But is there a more pythonic/compact way to do this? Maybe using dict comprehension?

You can use dictionary comprehension.

result = {name['name']: name for k, v in original.items() for name in v}

The inner for loop will iterate through all the key value pairs and the outer will iterate through each name in each value.

Yes, just rewrite your loops as a dict comprehension:

original = {
    1: [{'name': 'Sam'}, {'name': 'Mahmoud'}, {'name': 'Xiao'}], 
    2: [{'name': 'Olufemi'}, {'name': 'Kim'}, {'name': 'Rafael'}]
}

result = {d['name']: d for l in original.values() for d in l}

from pprint import pprint
pprint(result)

Output:

{'Kim': {'name': 'Kim'},
 'Mahmoud': {'name': 'Mahmoud'},
 'Olufemi': {'name': 'Olufemi'},
 'Rafael': {'name': 'Rafael'},
 'Sam': {'name': 'Sam'},
 'Xiao': {'name': 'Xiao'}}

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