0

Let's say I have two dictionaries:

dict1 = {"name": "", "full_name": {"first_name": "", "last_name": ""}}
dict2 = {"name": "JD", "full_name": {"first_name": "John", "last_name": "Doe"}, "filled_key": "something", "unfilled_key": ""}

I would like to merge them so that dict1's keys contains all the values from dict2's keys. However, it should not include empty keys from dict2. Something like this should be the output:

merged =  {"name": "JD", "full_name": {"first_name": "John", "last_name": "Doe"}, "filled_key": "something"}

I was able to merge them like follows:

merged = {**dict1, **dict2}

but this also copies over the empty keys from dict2. Any idea on how this can be achieved without copying over empty keys?

Aizaz
  • 39
  • 7

2 Answers2

1

Simply filter out the empty values before merging.

merged = {**dict1, **{k: v for k, v in dict2.items() if v}}
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • 1
    I think this would work but there will be some edge cases which it can't tackle (e.g. nested keys in dict2 which are empty and should be filtered out ```("full_name": {"first": "john", "last": ""}``` -> here, last should be filtered out – Aizaz Jan 21 '22 at 10:06
  • @Aizaz then you would have to write a function that recursively descends into subdicts and removes the empty values. This is out of scope for your original question and [already answered](https://stackoverflow.com/questions/27973988/how-to-remove-all-empty-fields-in-a-nested-dict). – timgeb Jan 21 '22 at 10:09
0

There is no such thing as an empty key. To the python interpreter, an empty string is as much a valid value as any other string, except that its conversion to boolean evaluates to true. The reason, why the "empty keys" as you call them from dict1 are not kept when you merge the dicts is that they are overwritten by the keys and values of dict2, since dict2 has the same keys. If you want to join two dicts and leave out all the key-value pairs where the value is an empty string, you could do something like this:

new_dict = dict()
for k, v in dict1.items():
    if v != "":
        new_dict[k] = v
for k, v in dict2.items():
    if v != "":
        new_dict[k] = v
sunnytown
  • 1,844
  • 1
  • 6
  • 13