Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting list to dict python

Given a list:

source = [{'A':123},{'B':234},{'C':345}]

I need a dict from this list in the format:

newDict  = {'A':123,'B':234,'C':345}

What is the syntactically cleanest way to accomplish this?

like image 602
NTP Avatar asked Mar 02 '17 14:03

NTP


1 Answers

Use a dict-comprehension:

>>> l = [{'A':123},{'B':234},{'C':345}]
>>> d = {k: v for dct in l for k, v in dct.items()}
>>> d
{'A': 123, 'B': 234, 'C': 345}

However it's probably opinion-based if that's the "syntactically cleanest way" but I like it.

like image 162
MSeifert Avatar answered Oct 27 '22 13:10

MSeifert