Convert list to python dict

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 clean way to do this?

+6
source share
3 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, this is probably opinion based if it's a “syntactically clean way”, but I like it.

+6
source

Here's an additional approach, given here, to give you an idea of ​​how Python implements a functional programming method called abbreviation through the reduce() function. In Python 3, reduce() is in the functools package . In Python 2, reduce() is a built-in function . I am using Python 3 in the following example:

 from functools import reduce # don't import if you are using Python 2 def updater(dict_orig, dict_add): dict_orig.update(dict_add) return dict_orig new_dict = reduce(updater, l, dict()) 

The first argument to reduce() is a function to work with iterable, the second is iteration (your list is l ), and the third is an optional initializer object, which is placed at the top of the list reduce.

At each step of reduction, an object is required that must work: namely, the result of the previous step. But dict.update() does not return anything, so we need the updater() function above, which performs the update, and then returns the dict updated, thereby providing the necessary object for the next step. If it were not for dict.update() that has no return value, all this would be single-line.

Since dict.update() works directly with the original dict , we need this optional empty dict() initialization object to start undoing - without it, the first dict in your original list l will be changed,

For all these reasons, I understand the @MSeifert dict-assrehension approach very well, but I posted this anyway to illustrate the Python shortcut for you.

+1
source

If you use it often, you may need to define a merge function that you can pass to reduce :

 from functools import reduce # Needed for Python3 source = [{'A':123},{'B':234},{'C':345}] def merge(a,b): d = a.copy() d.update(b) return d print(reduce(merge, source)) #=> {'A': 123, 'C': 345, 'B': 234} 
0
source

Source: https://habr.com/ru/post/1015408/


All Articles