Combine dictionaries in different lists in Python

I need to combine 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'},...]

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

So, in the end, I want to get:

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'} ]

etc.

When dict2exhausted, it should start from the first element again.

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

+4
4

zip itertools.cycle .

from itertools import cycle

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

, .

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))]
+7

zip():

res = []

for i, j in zip(dict1, dict2):
    res.append(i)
    res[-1].update(j)

dicts , itertools.izip_longest() fillvalue, {}:

res = []

for i, j in itertools.izip_longest(dict1, dict2, fillvalue={}):
    res.append(i)
    res[-1].update(j)
0

Using modulo:

new_list = []
x = len(dict2)
for v, item in enumerate(dict1):
    z = item.copy()
    z['Place'] = dict2[v % x]['Place']
    new_list.append(z)
0
source

How to simply create an empty dictionary called resultand simply update it with a list of existing dictionaries that you want to combine, for example:

def merge_dicts(*dict_args):
    """
    Given any number of dicts, shallow copy and merge into a new dict,
    precedence goes to key value pairs in latter dicts.
    :param dict_args: a list of dictionaries
    :return: dict - the merged dictionary
    """
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result
0
source

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


All Articles