简体   繁体   中英

Find the key with minmum average value in two dictionaries in Python?

I have two dictionaries in the following example.

d1 = {'A' : 1, 'B' : 2,'C' : 9}
d2 = {'A' : 5, 'B' : 1,'C' : 10}

Now, to find get the key with Min value, I simply use

min_d1 = min(d1, key=d1.get)
min_d2 = min(d2, key=d2.get)

print(min_d1, min_d2) # A B

My question is if there is an efficient way to find the key that has the minimum average in the two above dictionaries without having to iterate over all the dics keys? Eg, in the above example I expect to get B as the output.

You can use collections.Counter :

>>> from collections import Counter
>>> d3 = Counter(d1) + Counter(d2)
>>> min(d3, key=d3.get)
'B'

It uses the fact that the key with minimum average will also have the minimum sum.

If you want to do it without importing anything else, you could do the following:

>>> min(d1, key=lambda k: d1[k] + d2[k])
'B'

Although it iterates over all the keys anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM