简体   繁体   中英

Convert list of dictionaries into dict

I have the following list of one-element dictionaries:

[{'\xe7': '\xe7\x95\xb6\xe6\x96\xb0\x.'}, {'...\xe6\x991\xe7\xa8\x': 'asdf'}]

How would I convert this into a dict? To get:

{
    '\xe7': '\xe7\x95\xb6\xe6\x96\xb0\x.',
    '...\xe6\x991\xe7\xa8\x': 'asdf'
}

You can do it with a dict comprehension :

{k:v for element in dictList for k,v in element.items()}

This syntax only works for Python versions >= 2.7 though. If you are using Python < 2.7, you'd have to do something like:

dict([(k,v) for element in dictList for k,v in element.items()])

If you're unfamiliar with such nesting inside a comprehension, what I've done is equivalent to:

newDict = {}
for element in dictList:
    for k,v in element.items():
        newDict[k] = v

I'd probably just do:

dct = {}
for sub_dict in lst:
    dct.update(sub_dict)

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