Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
}
like image 468
David542 Avatar asked Dec 05 '22 04:12

David542


1 Answers

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
like image 128
Eithos Avatar answered Dec 06 '22 18:12

Eithos