Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting the missing values of dictionary with default value python

Tags:

python

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

like image 492
frazman Avatar asked Mar 21 '12 19:03

frazman


3 Answers

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"
like image 116
phihag Avatar answered Oct 06 '22 16:10

phihag


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
like image 44
ovgolovin Avatar answered Oct 06 '22 15:10

ovgolovin


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)
like image 44
Sid Avatar answered Oct 06 '22 17:10

Sid