Home > OS >  How to merge sub_dictionaries of a list [duplicate]
How to merge sub_dictionaries of a list [duplicate]

Time:10-03

I am working with a dataset and after performing some evaluations I got the following output

[{'Afghanistan': 0.0}, {'Albania': 0}, {'Algeria': 1.0}, {'Angola': 1.0769230769230769}, {'Argentina': -0.23076923076923078}, {'Armenia': 8.0}, {'Australia': -0.09090909090909091}, {'Azerbaijan': 2.875}, {'Bahamas': -0.7857142857142857}, {'Belarus': 2.25}, {'Belize': 1.5}, {'Benin': -0.34782608695652173}, {'Bhutan': 2.0}, {'Bolivia (Plurinational State of)': 1.2173913043478262}, {'Botswana': -0.2857142857142857}, {'Brazil': 0.5}, {'Burkina Faso': -1.25}, {'Burundi': -1.25}, {'Cabo Verde': 0.5}, {'Cambodia': 0.6949152542372882}, {'Cameroon': 0.42857142857142855}, {'Central African Republic': -0.7333333333333333}, {'Chad': -0.36585365853658536}, {'Chile': 0.6774193548387096}, {'Colombia': -0.2558139534883721}, {'Comoros': 0}, {'Congo': -0.7407407407407407}, {'Costa Rica': 0.1}, {'Croatia': -1.0}, {'Cuba': 4.0}, {"C™te d'Ivoire": -0.7142857142857143}, {'Democratic Republic of the Congo': -0.7}, {'Denmark': -0.23076923076923078}, {'Djibouti': 1.6486486486486487},... ]

Now this looks almost good, the only problem is that I need to get just one big dictionary like this

{'Afghanistan': 0.0,'Albania': 0,'Australia': -0.09090909090909091 ... }

Therefore I need to merge all these sub_dictionaries. Does someone know how to do it?

CodePudding user response:

Assuming that each dict in your list contains one key only, you can do the following:

merged_dict = {item.keys[0]: item.values[0] for item in data}

In case there might be several keys, you can do:

merged_dict = dict()
for item in data:
    merged_dict.update(item)

CodePudding user response:

Iterate over the list and merge all subdictionaries in a new one using either the |= operator (if using python3.9) or .update method. Here an exmaple

lst = # from above
new_dict = {}
for d in lst:
    new_dict |= d        # from python3.9
    #new_dict.update(d)

print(new_dict)

Dictionaries have unique keys so, when merging, duplicate keys will not taken into account (the last added will count)

CodePudding user response:

Just pop the items into a new dict.

merged = dict(map(dict.popitem, lst))
  • Related