将元素添加到词典列表

时间:2016-08-18 19:27:43

标签: python list dictionary

通常情况下,我不会发布这个,但过去10个小时它一直让我发疯...

我有2个词典列表。但他们要么没有,要么有1个或2个共同点。如果在迭代第二个列表中的元素时,我匹配第一个列表中的键值对,那么我必须将这些元素添加到第一个列表中,在那个特定的位置

所以第一个列表是这样的:

list1 = [{'key11':'value11', 'key12':'value12', ...}, {'key11':'value111', 'key121':'value121', ...}]

和list2类似于上面提到的列表:

list2 = [{'2key11':'value11', 'key12':'value12', '2key13': 'value'...}, {...}]

请注意,key12在两个列表中都是相同的。所以我想要的最终产品是:

>list1 = list1 (some operation) list2
>list1
>[{'key11':'value11', 'key12':'value12', '2key11':'value11', ...}, {'key11':'value111', 'key121':'value121', ...}]

请注意,在所需的输出中,我已将所有第二个列表字典元素添加到与list1(第一个字典)中的key12相对应的字典中。

到目前为止,我一直在手动进行,结果并不好。 我的代码是这样的:

for i in range(len(list)):
    # Now we need to map the panther data as well.
    for pitem in plist:
        # match the id's to the mapped symbols

        if list[i]['key_id1'] == pitem['key_id1']:
            if list[i]['key_id2'] == 'n/a':
                list[i]['key_id2'] = pitem['key_id2']
            list[i]['somekey1'] = panther_item['somekey1']
            list[i]['somekey2'] = panther_item['somekey2']
            list[i]['somekey3'] = panther_item['somekey3'] # <- WHY IS THIS GIVING ME A KEY ERROR AND NOT THE ONE ABOVE IT? Both didnt exist in the dictionary stored in list.
            list[i]['somekey4'] = panther_item['somekey4']
            list[i]['somekey5'] = panther_item['somekey5']

        elif list[i]['key_id2'] == pitem['key_id2']:
            if list[i]['key_id1'] == 'n/a':
                list[i]['key_id1'] = pitem['key_id1']
            list[i]['somekey1'] = panther_item['somekey1']
            list[i]['somekey2'] = panther_item['somekey2']
            list[i]['somekey3'] = panther_item['somekey3']
            list[i]['somekey4'] = panther_item['somekey4']
            list[i]['somekey5'] = panther_item['somekey5']

但是我在{3}上获得了keyError一些关键字3&#39;。为什么&some 39; somekey3&#39;而不是#some; somekey2&#39;?两个都不在那里。我每次都在这次迭代中加入它们。当我在编辑之前打印2个列表时,它们是正确的。这可能会出现什么问题?

2 个答案:

答案 0 :(得分:0)

我认为我的问题是正确的,您想在2个列表中找到两个相应字典的并集吗?下面的代码应该实现这一点。请记住,如果相应键的值不同,y(list2词典)将优先于x。

list3 = []
for x,y in zip(list1, list2):
    z = x.copy()
    for key, value in y.iteritems():
        if value != 'n/a':
            z[key] = value
    list3.append(z)

答案 1 :(得分:-1)

也许我说得对,你想将list2中所有字典值添加到list1中的第一个字典中,其中包含'key12'?以下代码应该这样做。

first_dict = next(d for d in list1 if 'key12' in d)
for d in list2:
    first_dict.update(d)

如果你想将它们添加到list1中的第一个字典中,该字典在同一个位置上具有来自list2的dict的公共密钥,那么:

first_dict = next(a for a, b in zip(list1, list2) if set(a.keys()) & set(b.keys()))
for d in list2:
    first_dict.update(d)