-1

I would like dict3 to match dict2 after running it through this loop. It doesn't have to be a loop if there is an easier way.

dict1={'key1' : 'val1', 'key2' : ''}
dict2={'key1' : 'val1', 'key2' : 'val2'}
dict3=dict1

#pseudocode
for key in dict1.keys():
        if value is not None:
            #no need to do anything
        else:
            dict3[value] = dict2[value]

What I would like is for dict3 to contain keys and values matching dict2.

wjandrea
  • 23,210
  • 7
  • 49
  • 68
Blake Shurtz
  • 271
  • 2
  • 12
  • 1
    So use `if value == ''`... Is that not obvious? In any case, what's your question? Please [edit] to clarify. What have you already tried, and how has it not worked? BTW, are you aware that `dict3 is dict1`? – wjandrea Aug 27 '20 at 01:17
  • 1
    For how to iterate over a dict's keys and values, see [this answer](https://stackoverflow.com/a/7409280/4518341). For how to copy a dict, see [this other answer](https://stackoverflow.com/a/2465932/4518341). Maybe you want to simply do `dict3 = dict2.copy()`? – wjandrea Aug 27 '20 at 01:24

1 Answers1

1

I believe you need a dict comprehension with .copy

Ex:

dict1 = {'key1' : 'val1', 'key2' : ''}
dict2 = {'key1' : 'val1', 'key2' : 'val2'}
dict3 = {k: v if v else dict2.get(k, v) for k, v in dict1.items() }
print(dict3) #--> {'key1': 'val1', 'key2': 'val2'}
Rakesh
  • 78,594
  • 17
  • 67
  • 103