Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to calculate equal parts of two dictionaries?

I have a problem with combining or calculating common/equal part of these two dictionaries. In my dictionaries, values are lists:

d1 = {0:['11','18','25','38'], 
      1:['11','18','25','38'], 
      2:['11','18','25','38'], 
      3:['11','18','25','38']}

d2 = {0:['05','08','11','13','16','25','34','38','40', '43'], 
      1:['05', '08', '09','13','15','20','32','36','38', '40','41'], 
      2:['02', '08', '11', '13', '18', '20', '22','33','36','39'], 
      3:['06', '11', '12', '25', '26', '27', '28', '30', '31', '37']}

I'd like to check "d2" and know if there are numbers from "d1". If there are some, I'd like to update one of them with new data or receive 3rd dictionary "d3" with only the values that are identical/equal in both "d1" and "d2" like:

d3 = {0:['11','25','38'], 1:['38'], 2:['11','18'], 3:['11','25']} 

Can anyone help me with this?

My fault I forgot to be more specific. I'm looking for a solution in Python.

like image 812
elfuego1 Avatar asked Dec 18 '22 08:12

elfuego1


1 Answers

Assuming this is Python, you want:

dict((x, set(y) & set(d1.get(x, ()))) for (x, y) in d2.iteritems())

to generate the resulting dictionary "d3".

Python 3.0+ version

>>> d3 = {k: list(set(d1.get(k,[])).intersection(v)) for k, v in d2.items()}
{0: ['11', '25', '38'], 1: ['38'], 2: ['11', '18'], 3: ['11', '25']}

The above version (as well as Python 2.x version) allows empty intersections therefore additional filtering is required in general case:

>>> d3 = {k: v for k, v in d3.items() if v}

Combining the above in one pass:

d3 = {}
for k, v in d2.items():
    # find common elements for d1 & d2
    v3 = set(d1.get(k,[])).intersection(v)
    if v3: # whether there are common elements
       d3[k] = list(v3) 

[Edit: I made this post community wiki so that people can improve it if desired. I concede it might be a little hard to read if you're not used to reading this sort of thing in Python.]

like image 130
6 revs, 2 users 69% Avatar answered Dec 27 '22 18:12

6 revs, 2 users 69%