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.
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".
>>> 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.]
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