开发者

Combining entries, filtering of Python dictionaries

I have two large lists that are filled with dictionaries. I need to combine the entries if a value from dict2==dict1 and place the newly combined matches somewhere else. I'm having trouble explaining it.

List one contains:

{'keyword':value, 'keyword2':value2}

List two:

{'keyword2':value2, 'keyword3':value3}

I want a new list with dictionaries including keyword1, keyword2, and keyword3 if both lists share the same 'ke开发者_如何学编程yword2' value. What's the best way to do this? When I try, I only come up with tons of nested for loops. Thanks


If you don't care about "conflicts", i.e. that the same key is mapped to different values in two dicts, you can use the update method of dicts:

>>> d1 = {'keyword': 1, 'keyword2': 2}
>>> d2 = {'keyword2': 2, 'keyword3': 3}
>>> d = {}
>>> d.update(d1)
>>> d
{'keyword2': 2, 'keyword': 1}
>>> d.update(d2)
>>> d
{'keyword3': 7, 'keyword2': 2, 'keyword': 1}

Assuming your dicts are stored in a large list named dict_list:

total = {}
for d in dict_list:
    total.update(d)


Loop over one dictionary, comparing individual elements to the other dictionary. Like this, where dict1 and dict2 are the originals, and dict3 is the result:

dict3 = dict1
for k in dict2:
    if k in dict1:
        # The key is in both dictionaries; we've already added dict1's version
        if dict1[k] != dict2[k]:
            pass # The dictionaries have different values; handle this as you like
    else
        # The key is only in dict2; add it to dict3
        dict3[k] = dict2[k]

You weren't clear on what behavior you wanted if the two dictionaries have different values for some key; replace the "pass" with whatever you want to do. (As written, it will keep the value from dict1. If you don't want to include either value, replace the pass with del dict3[k].)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜