views:

69

answers:

2

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 'keyword2' value. What's the best way to do this? When I try, I only come up with tons of nested for loops. Thanks

A: 

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

Etaoin
+2  A: 

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)
jellybean
OP writes that only shared values should be in the new list, so he does care about conflicts - he just didn't state how the program should behave in such a case.
Tim Pietzcker