1

I would like to update my dictionary. If the key already exists in a dictionary then I would like to add new values to that key (from another dictionary). If the key does not exist in the dictionary, then I would like to add a new key (from another dictionary).

In other words, I just want updated keys with new added (not overridden) values (if the keys exist in both dictionaries) and new keys (if the key exists in the new dictionary)

This is an example of the dictionaries I currently have:

     global_dict = {'abc': 123, 'def': 456}
     new_dict={'def':789, 'ghi': hello}

What I want is for the global dict to finally look like this:

     global_dict={'abc':123, 'def'=[456, 789], 'ghi'=hello}

This is the code I currently have:

    for key,val in new_dict.items():
       if key in global_dict:
          global_dict[key]=[global_dict[key],val]
       else:
          global_dict.update(new_dictionary)

This currently does not work, I'm not sure what is wrong with my solution. Any tips?

sos.cott
  • 435
  • 3
  • 17

1 Answers1

3

You update global_dict with the entire new_dict when key isn't already in global_dict, so you end up overwriting the sub-list you created for keys that do match. You should update just the value for the key that isn't already in global_dict.

Change:

global_dict.update(new_dictionary)

to:

global_dict[key] = val
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • I just tried this but the new keys from the new_dictionary are not added to the global_dictionary. – sos.cott Aug 31 '18 at 03:04
  • It works for me as `global_dict` becomes `{'abc': 123, 'def': [456, 789], 'ghi': 'hello'}`. Can you show me your new code if it doesn't work for you? – blhsing Aug 31 '18 at 03:05
  • The keys that are not in `global_dict` but only in `dict_2014` did not show up. What kind of content description are you looking for `dict_2014`? It's a mix of strings and floats. – sos.cott Aug 31 '18 at 03:08
  • 1
    That code looks correct. What are the content of `global_dict` and `dict_2014` in your actual run? Which keys in `dict_2014` did not show up in `global_dict` after you run this code? – blhsing Aug 31 '18 at 03:10
  • The keys that were only in `dict_2014` did not show up in `global_dict`. The contents of both dictionaries included both strings and floats. – sos.cott Aug 31 '18 at 03:24
  • The sample data in your question works with the new code (can you confirm?), so there must be something unusual with the actual data you use that causes the unexpected behavior. There isn't much I can help without the actual data you use at this point. – blhsing Aug 31 '18 at 03:29
  • 1
    This works now! there was a bug in my previous code! Thank you. – sos.cott Aug 31 '18 at 03:31