majache
0
Q:

merge a list of dictionaries python

dict1 = {'a': 10, 'b': 8} 
dict2 = {'d': 6, 'c': 4} 
dict2.update(dict1)
5
dict1 = {'color': 'blue', 'shape': 'square'}
dict2 = {'color': 'red', 'edges': 4}

dict1.update(dict2) #if a key exists in both, it takes the value of the second dict
# dict1 = {'color': 'red', 'shape': 'square', 'edges': 4}
# dict2 is left unchanged
3
>>> from collections import ChainMap
>>> a = [{'a':1},{'b':2},{'c':1},{'d':2}]
>>> dict(ChainMap(*a))
{'b': 2, 'c': 1, 'a': 1, 'd': 2}
0
>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 10, 'c': 11}
>>> z = {**x, **y} #In Python 3.5 or greater only
>>> print(z)
{'a': 1, 'b': 10, 'c': 11}
1
import pandas as pd

l1 = [{'id': 9, 'av': 4}, {'id': 10, 'av': 0}, {'id': 8, 'av': 0}]
l2 = [{'id': 9, 'nv': 45}, {'id': 10, 'nv': 0}, {'id': 8, 'nv': 30}]

df1 = pd.DataFrame(l1).set_index('id')
df2 = pd.DataFrame(l2).set_index('id')
df = df1.merge(df2, left_index=True, right_index=True)
df.T.to_dict()
# {9: {'av': 4, 'nv': 45}, 10: {'av': 0, 'nv': 0}, 8: {'av': 0, 'nv': 30}}
0

New to Communities?

Join the community