在Python中合并不同列表中的词典

时间:2017-01-18 13:47:18

标签: python dictionary

我需要合并两个带字典的列表:

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中的值为:      dict2 = [{'Place': 'Home'}, {'Place':'Home'},{'Place':'Home'},{'Place':'Home'},{'Place':'Forest'},{'Place':'Forest'}...] 然后使用下面提到的相同方法合并字典。但我相信应该有一种方法可以在不改变dict2的情况下做到这一点。

4 个答案:

答案 0 :(得分:7)

我们将使用 swipe = new UISwipeGestureRecognizer( (s) => { if (s.Direction == UISwipeGestureRecognizerDirection.Up) { Console.WriteLine("up"); } }); itertools.cycle配对两个列表中的元素。

zip

如果您不想修改原始列表,则会更复杂一些。

from itertools import cycle

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

答案 1 :(得分:0)

您可以使用zip()

res = []

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

如果你的词组中的项目数不相同,则可以itertools.izip_longest()使用fillvalue param设置为{}

res = []

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

如何简单地创建一个名为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
相关问题