Home > Blockchain >  Loop over 2 dictionnaries and append several values to a key
Loop over 2 dictionnaries and append several values to a key

Time:10-27

I have 2 dictionnaries, the first one is showing some works:

d= {"a": "pompier", "b": "policier", "c": "tracteur"}

And the second one the adjectives associated with works which are list type

d1 = {"a": "[gentil, fort]", "b": "[juste, amicale]", "c": "[fonctionnel, fort, utile]"}

I want to append the value from the d1 dictionnary into the d dictionnary to have something looking like this

d2 = {"a": "pompier", "[gentil, fort]", "b": "policier", "[juste, amicale]", "c": "tracteur", "[fonctionnel, fort, utile]"}

I need to precise, I don't know if there is (in my original file), key from d1 that are not in d dictionnary...

I've tried this code but it returns an error

or key, value in d.items():
for key1, value1 in d1.items():
    if key in d1:
        d1[key].append[value1]
    print(d1)

    Traceback (most recent call last):
  File "<string>", line 7, in <module>
AttributeError: 'str' object has no attribute 'append'

Thank you in advance

CodePudding user response:

d= {"a": "pompier", "b": "policier", "c": "tracteur"}
d1 = {"a": "[gentil, fort]", "b": "[juste, amicale]", "c": "[fonctionnel, fort, utile]"}
d2 = dict()
for key, value in d.items():
    if d1.get(key):
        d2[key] = [value, d1.get(key)]
    else:
        d2[key] = value

print(d2)

First of all, you need to define d2. Secondly, you have strings, not lists, so you cannot use append. Instead, you must add them to the list. Here, if a key doesn't exist in d1, it's going to remain just a single value and if it exists, it'll add them to the list.

You have 2 options here. If you want values to always be in a list, just put d2[key] = [value]

If you have keys in d1 that do not exist in d, you should do another loop through d1.items() and add just the missing ones:

for key, value in d1.items():
    if key not in d.keys():
        d2[key] = value
  • Related