Comparing The Values Of Two Dict_values Based On Certain Criteria
I have two dictionaries that I'd liked to compare their dict_values based on certain criteria, say the value at index 0 and 2 on their respective dict_values have to be the same to
Solution 1:
I'm not sure if this is much better, but the following should work:
import operator
import sys
py3k = sys.version_info[0] > 2
a = dict()
b = dict()
a[1,3] = 5, 6, 7
b[1,4] = 5, 9, 7if(py3k):
a_tuple = next(iter(a.values()))
b_tuple = next(iter(b.values()))
else:
a_tuple = a.values()[0]
b_tuple = b.values()[0]
cmp_key=operator.itemgetter(0,2)
if cmp_key(a_tuple) == cmp_key(b_tuple):
print('Equal')
The comparison is a little more clean and I use next
and iter
to get the first tuple in the dictionary if using python 3.
Of course, the better solution would be change the data structure so you're not constantly dealing with dictionaries with only 1 item.
Solution 2:
Not much difference, only optimization i found is a_tuple = a.values()[0] b_tuple = b.values()[0]
Actually dict.values gives you tuple only. You are convrting it to list and then again to tuple
Post a Comment for "Comparing The Values Of Two Dict_values Based On Certain Criteria"