I have one defaultdict(list) and other normal dictionary
A = {1:["blah", "nire"], 2:["fooblah"], 3:["blahblah"]}
B = {1: "something" ,2:"somethingsomething"}
now lets say that i have something like this
missing_value = "fill_this"
Now, first I want to find what are the keys in B missing from A (like 3 is missing)
and then set those keys to the values missing_value
?
What is the pythonic way to do this?
Thanks
You can use setdefault
:
for k in A:
B.setdefault(k, "fill_this")
This is essentially the same as the longer:
for k in A:
if k not in B:
B[k] = "fill_this"
However, since setdefault
only needs to lookup each k
once, setdefault
is faster than this "test&set" solution.
Alternatively (and probably slower), determine the set difference and set (no pun intended) those values:
for k in set(A).difference(B):
B[k] = "fill_this"
The solution is to go through A
and update B
where necessary. It would have O(len(A))
complexity:
for key in A:
if key not in B:
B[key] = missing_value
Here's one way:
def test():
A = {1:"blah", 2:"fooblah", 3:"blahblah"}
B = {1: "something" ,2:"somethingsomething"}
keys=set(A.keys()).difference(set(B.keys()))
for k in keys:
B[k]="missing"
print (B)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With