Answers for "combine list of dictionaries python"

23

create dictionary python from two lists

>>> keys = ['a', 'b', 'c']
>>> values = [1, 2, 3]
>>> dictionary = dict(zip(keys, values))
>>> print(dictionary)
{'a': 1, 'b': 2, 'c': 3}
Posted by: Guest on May-21-2020
1

merged all dictionaries in a list python

>>> result = {}
>>> for d in L:
...    result.update(d)
... 
>>> result
{'a':1,'c':1,'b':2,'d':2}
Posted by: Guest on August-03-2020
1

how to merge a list of dictionaries in python

from collections import defaultdict
dict_list = {
	1: [{
			"x": "test_1",
			"y": 1
		},
		{
			"x": "test_2",
			"y": 1
		}, {
			"x": "test_1",
			"y": 2
		}
	],
}
print(dict_list) # {1: [{'x': 'test_1', 'y': 1}, {'x': 'test_2', 'y': 1}, {'x': 'test_1', 'y': 2}]}

data = dict()
for key, value in dict_list.items():
    tmp = defaultdict(int)
    for index, item in enumerate(value):
        tmp[item.get("x") ] += item.get("y")

    for tmp_key, tmp_value in tmp.items():
        data.setdefault(key, []).append(
            {
                "x": tmp_key,
                "y": tmp_value
            }
        )
print(data) # {1: [{'x': 'test_1', 'y': 3}, {'x': 'test_2', 'y': 1}]}

# test 1 values is added together
Posted by: Guest on February-27-2021
0

merge a list of dictionaries python

>>> from collections import ChainMap
>>> a = [{'a':1},{'b':2},{'c':1},{'d':2}]
>>> dict(ChainMap(*a))
{'b': 2, 'c': 1, 'a': 1, 'd': 2}
Posted by: Guest on October-13-2020
0

python merge list of dict into single dict

l = [{'a': 0}, {'b': 1}, {'c': 2}, {'d': 3}, {'e': 4, 'a': 4}]
d = {k: v for x in l for k, v in x.items()}
print(d)
# {'a': 4, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
Posted by: Guest on September-22-2021
0

merge two list of dictionaries python with string

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}}
Posted by: Guest on April-07-2020

Code answers related to "combine list of dictionaries python"

Python Answers by Framework

Browse Popular Code Answers by Language