Python miminum length/max value in dictionary of lists

末鹿安然 提交于 2019-12-23 06:26:11

问题


Had to re-write the question due to changed requirements.

I have a dictionary such as the following:

d = {'a': [4, 2], 'b': [3, 4], 'c': [4, 3], 'd': [4, 3], 'e': [4], 'f': [4], 'g': [4]}

I want to get the keys that are associated with the smallest length in the dictionary d, as well as those that have the maximum value.

In this case, the keys with the smallest length (smallest length of lists in this dictionary) should return

'e, 'f', 'g'

And those with the greatest value(the sum of the integers in each list) should return

'b' 'c'

I have tried

min_value = min(dict.itervalues())
min_keys = [k for k in d if dict[k] == min_value]

But that does not give me the result I want.

Any ideas?

Thanks!


回答1:


def get_smallest_length(x):
    return [k for k in x.keys() if len(x.get(k))==min([len(n) for n in x.values()])]

def get_largest_sum(x):
    return [k for k in x.keys() if sum(x.get(k))==max([sum(n) for n in x.values()])]

x = {'a': [4, 2], 'c': [4, 3], 'b': [3, 4], 'e': [4], 'd': [4, 3], 'g': [4], 'f': [4]}

print get_smallest_length(x)
print get_largest_sum(x)

Returns:

['e', 'g', 'f']
['c', 'b', 'd']


来源:https://stackoverflow.com/questions/11730552/python-miminum-length-max-value-in-dictionary-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!