簡體   English   中英

在Python中合並不同列表中的詞典

[英]Merge dictionaries in different lists in Python

我需要合並兩個帶有字典的列表:

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

第一個列表中有56個元素(56個字典),第二個列表中有14個元素(dict2)。 我想要做的是將第一個元素從dict2插入到dict 1的前四個元素並重復該過程,直到dict1中的所有56個元素都有{Place:x}。

所以我最終得到的是:

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

等等..

dict2耗盡時,它應該再次從第一個元素開始。

所以我更新了問題。 我對此問題的第一個看法是增加相同鍵的數量: dict2 = [{'Place': 'Home'}, {'Place':'Home'},{'Place':'Home'},{'Place':'Home'},{'Place':'Forest'},{'Place':'Forest'}...]中的值為: dict2 = [{'Place': 'Home'}, {'Place':'Home'},{'Place':'Home'},{'Place':'Home'},{'Place':'Forest'},{'Place':'Forest'}...]然后使用下面提到的相同方法合並字典。 但我相信應該有辦法在不改變dict2的情況下做到這一點。

我們將使用zipitertools.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))]

你可以使用zip()

res = []

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

如果你的dicts中的項目數不相同,你可以使用設置為{} fillvalue param的itertools.izip_longest()

res = []

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

使用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)

如何簡單地創建一個名為result的空字典,只需使用您想要合並的現有字典列表進行更新,例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM