0

I have two dicts:

dict1={"test":345,"testing":123,"reality":2,"factor":5,"user":1}
dict2={"newone":123,"test":4,"reality":"4","edu":2}

Now,I want to form a new dictionary as follows:

dict3={"test":[345,4],"testing":[123,0],
"reality":[2,4],"factor":[5,0],"user":[1,0],"newone":[0,123],"edu":[0,2]}

I want to add 0 if any key is not present in dict1 at the first index and add 0 if any key is not present in dict2. How can I achieve this? I have tried the following code:


    for keys1,values1,keys2,values2 in zip(dict1.items(),dict2.items()):
        if keys1 not in dict2.keys():
            dict2.keys().append(0)
        elif keys2 not in dict1.keys():
            dict1.keys().append(0)
        else:
            pass

Sam
  • 131
  • 1
  • 9

2 Answers2

2

use dict.get() to return a default value if the key is not in the dictionary:

{x:[dict1.get(x,0),dict2.get(x,0)] for x in list(dict1.keys()) + list(dict2.keys())}

gives

{'test': [345, 4],
 'testing': [123, 0],
 'reality': [2, '4'],
 'factor': [5, 0],
 'user': [1, 0],
 'newone': [0, 123],
 'edu': [0, 2]}
Z Li
  • 4,133
  • 1
  • 4
  • 19
2

Use dict.keys() union and dict.get():

dict1 = {"test": 345, "testing": 123, "reality": 2, "factor": 5, "user": 1}
dict2 = {"newone": 123, "test": 4, "reality": "4", "edu": 2}

dict3 = {k:[dict1.get(k,0), dict2.get(k,0)] for k in dict1.keys() | dict2.keys()}

print(dict3)

Gave me:

{'testing': [123, 0], 'edu': [0, 2], 'factor': [5, 0], 'user': [1, 0], 'newone': [0, 123], 'reality': [2, '4'], 'test': [345, 4]}
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49