Reputation: 1154
I have 3 dictionaries
demo1={'1':['a','b','c'],'2':['x','y'],...}
demo2={1:['b','c','e'],2:['x','z','w'],...}
coef={'1':5,'2':6,...}
I want output like this
output={1:2/5,2:1/6,...}
where in output value numerator is number of matching values between demo1 and demo2, and denominator is corresponding value in coef.
ex. for key=1 in demo1 and demo2, 'b' and 'c' match, so numerator is 2, and coef for key=1 is 5
I've tried to do it via for loops, but I'm having too much of them, is there more efficient way?
PS: key in demo1 is string, and in demo2 is int, that doesn't matter what returns in output. Either string or int is fine
Upvotes: 2
Views: 49
Reputation: 4606
Use the length of the merged sets
d = {k: len(set(demo1[k]) & set(demo2[int(k)]))/v for k, v in coef.items()}
Upvotes: 0
Reputation: 71461
You can use a dictionary comprehension:
demo1={'1':['a','b','c'],'2':['x','y']}
demo2={1:['b','c','e'],2:['x','z','w']}
coef={'1':5,'2':6}
result = {i:sum(c in demo1[i] and c in demo2[int(i)] for c in set(demo1[i]+demo2[int(i)]))/coef[i] for i in demo1}
Output:
{'1': 0.4, '2': 0.16666666666666666}
Upvotes: 3
Reputation: 946
output = {len(set(demo1[i]) & set(demo2[int(i)])) / coef[i] for i in demo1}
s1 & s2
is the intersection of the sets s1
and s2
len(s)
will give you the number of elements in the set s
Upvotes: 2
Reputation: 36691
You can convert the values to sets and find the length of the intersections
{k:len(set(demo1.get(k)).intersection(demo2.get(int(k))))/v for k,v in coef.items()}
{'1': 0.4, '2': 0.16666666666666666}
Upvotes: 2
Reputation: 71600
Easier:
print({k:len([i for i in demo1[k] if i in demo2[int(k)]])/v for k,v in coef.items()})
Output:
{'1': 0.4, '2': 0.16666666666666666}
Upvotes: 3