How to append only new key pair from one dictionary to another in Python?

hr2406 :

I have these 2 dictionaries:

Rorys_guests = {"Adam": 2, "Brenda": 3, "David": 1, "Jose": 3, "Charlotte": 2, "Terry": 1, "Robert": 4}

Taylors_guests = {"David": 4, "Nancy": 1, "Robert": 2, "Adam": 1, "Samantha": 3, "Chris": 5}

I want to check if a key (only the key) in Taylors_guests is already in Rorys_guests. If not, I want to append the key and value pair from Taylors to Rorys.

Note: Some key are the same in both dictionaries. I don't want to overwrite the values in Rorys_guests. I only want to append keys and values from Taylors dict that are not yet in the Rorys dict.

for i in Taylors_guests:
    print(i)
    if i in Rorys_guests:
        print("yes")
    else:
        Rorys_guests = Rorys_guests.get(i)

print(Rorys_guests)

I am a python noob, but still looked through many different sites and couldn't find a solution.

Thank you in advance!

FishingCode :

I believe you are very close, but I think this should do it:

Rorys_guests = {"Adam": 2, "Brenda": 3, "David": 1, "Jose": 3, "Charlotte": 2, 
"Terry": 1, "Robert": 4}

Taylors_guests = {"David": 4, "Nancy": 1, "Robert": 2, "Adam": 1, "Samantha": 
3, "Chris": 5}

for k,v in Taylors_guests.items():
   if k not in Rorys_guests.keys():
      Rorys_guests[k] = Taylors_guests[k]
print(Rorys_guests)

Output:

{'Adam': 2, 'Brenda': 3, 'David': 1, 'Jose': 3, 'Charlotte': 2, 'Terry': 1, 'Robert': 4, 'Nancy': 1, 'Samantha': 3, 'Chris': 5}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=16504&siteId=1