Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge dictionaries in different lists in Python

I need to merge two lists with dictionaries in them:

dict1 = [{'Count': '307', 'name': 'Other', 'Percentage': '7.7%'}, {'Count': '7,813', 'name': 'Other', 'Percentage': '6.8%'}...]
dict2 = [{'Place': 'Home'}, {'Place':'Forest'},...]

There are 56 elements in the first list (56 dictionaries) and 14 elements in the second list (dict2). What I want to do is inset first element from dict2 to first four elements of dict 1 and repeat the process until all 56 elements in dict1 have {Place:x}.

So eventually what I want to get is:

newdict = [{'Count': '307', 'name': 'Other', 'Percentage': '7.7%', 'Place': 'Home'}, {'Count': '7,813', 'name': 'Other', 'Percentage': '6.8%', 'Place':'Home'},{'Name': 'Other', 'Percentage': '6.6%', 'Place': 'Home', 'Count': '1,960'},{'Name': 'Other', 'Percentage': '7.6%', 'Place': 'Home', 'Count': '1,090'},{'Name': 'Other', 'Percentage': '7.6%', 'Place': 'Forest', 'Count': '1,090'} ]

and so on..

When dict2 is exhausted, it should start from first element again.

So I updated question. My first take on this problem was to increase number of same key:values in dict2 to: dict2 = [{'Place': 'Home'}, {'Place':'Home'},{'Place':'Home'},{'Place':'Home'},{'Place':'Forest'},{'Place':'Forest'}...] and then use the same method mentioned below to merge dictionaries. But I believe there should be a way to do this without changing dict2.

like image 587
Extria Avatar asked Mar 10 '23 03:03

Extria


1 Answers

We'll use zip and itertools.cycle to pair up elements from the two lists.

from itertools import cycle

for a, b in zip(dict1, cycle(dict2)):
    a.update(b)

If you don't want to modify the original list, it's a little more complex.

from itertools import cycle, chain

new_list = [{k:v for k, v in chain(a.items(), b.items())} for a, b in zip(dict1, cycle(dict2))]
like image 53
Patrick Haugh Avatar answered Mar 19 '23 08:03

Patrick Haugh