从列表中的字典中查找最高键值对

时间:2014-10-06 04:48:49

标签: python list dictionary nested

我正在尝试从列表中获取具有最高值的键。我该怎么做呢?顺便说一句,我是编程和python的新手,所以这主要是我自己的练习。

下面是一个列表中字典的基本信息示例,我希望能够获得具有最高键的值。在这种情况下,它将返回'Vinnie M'和'Zoey M'。

也许有更好的方法来构建这些数据,但我希望在词典中有更多信息,例如用户ID,投标时间等。此外,我还需要能够添加新用户而无需更改代码,在另一个函数中处理,所以不要担心添加新用户的建议,除非我的初始方法有缺陷。

userList = [
    {'Full Name' : 'Ryan R.', 'Bid Amount' : 4.30},
    {'Full Name' : 'Zoey M.', 'Bid Amount' : 5.20},
    {'Full Name' : 'Max D.', 'Bid Amount' : 3.90},
    {'Full Name' : 'Vinnie M', 'Bid Amount' : 5.20}
    ]

2 个答案:

答案 0 :(得分:0)

您可以将operator.itemgetter用于此目的..

import operator
dict =  [
{'Full Name' : 'Ryan R.', 'Bid Amount' : 4.30},
{'Full Name' : 'Zoey M.', 'Bid Amount' : 5.20},
{'Full Name' : 'Max D.', 'Bid Amount' : 3.90},
{'Full Name' : 'Vinnie M', 'Bid Amount' : 5.20}
]`

max(dict.iteritems(), key=operator.itemgetter(1))[0]

答案 1 :(得分:0)

>>> userList = [
...     {'Full Name' : 'Ryan R.', 'Bid Amount' : 4.30},
...     {'Full Name' : 'Zoey M.', 'Bid Amount' : 5.20},
...     {'Full Name' : 'Max D.', 'Bid Amount' : 3.90},
...     {'Full Name' : 'Vinnie M', 'Bid Amount' : 5.20}
...     ]
>>> D = {i['Full Name']: i['Bid Amount'] for i in userList}
>>> mx = max(D.values())
>>> [i for i in D if D[i] == mx]
['Vinnie M', 'Zoey M.']

您也可以在没有中间dict的情况下执行此操作。但似乎是一种不自然的数据结构,除非你可以有重复的全名

>>> mx = max(i['Bid Amount'] for i in userList)
>>> [i['Full Name'] for i in userList if i['Bid Amount'] == mx]
['Zoey M.', 'Vinnie M']
相关问题