I have an empty dict and I want to check if key is present on not, if key is not present create a list append a value to it. If it's already present then append new value to it. But I am seeing it returning None
# Code
policy_models = {}
res = ['1', '1', '2', '3', 'x']
for idx, r in enumerate(res):
p = policy_models.get(r, []).append(r)
print(idx, r,p)
# Output
0 1 None # See how we have None in output even though key is not present whereas it should be [1, 1]
1 1 None
2 2 None
3 3 None
4 x None
The above code is modified and it's creates a list
policy_models = {}
res = ['1', '1', '2', '3', 'x']
for idx, r in enumerate(res):
p = policy_models.get(r, [])#.append(r)
print(idx, r,p)
In above code I have commented append(r)
and got a list as expected.
# output
0 1 []
1 1 []
2 2 []
3 3 []
4 x []
How can I create a list and insert the value at the same time while extracting it from dict ? And why this behavior.
EDIT: Using set-default also didn't work
policy_models = {}
res = ['1', '1', '2', '3', 'x']
for idx, r in enumerate(res):
p = policy_models.setdefault(r, []).append(r)
print(idx, r,p)
# Output
0 1 None
1 1 None
2 2 None
3 3 None
4 x None
CodePudding user response:
You're looking for setdefault
:
policy_models.setdefault(r, []).append(...)