Reputation:
I have a list of dictionaries as follows, with different keys and values.
lst = [{'a': 15554}, {'v': 453}, {'a': 441742}, {'vb': 7785},
{'vv': 4275}, {'g': 7822}, {'l': 47537}, {'fg': 1144441565}]
I want to find which dictionary contains the highest value using python.
Ex:
fg: 1144441565
can somebody suggest me a code?
Thanks in advance.
Upvotes: 0
Views: 2000
Reputation: 195
You could do it simply by looping though the list of dictionaries and checking the value each time:
# Define the list
list1 = [{'a': 15554}, {'v': 453}, {'a': 441742}, {'vb': 7785},
{'vv': 4275}, {'g': 7822}, {'l': 47537}, {'fg': 1144441565}]
# Init variable to hold the maximum value and its corresponding key.
# We just initialize it as the value of the first element:
max_val_key = list1[0].keys()[0]
max_val = list1[0][max_val_key]
# Loop through it using the 'in' operator
for dict in list1:
key = dict.keys()[0]
val = dict[key]
# Check if current val is higher than the last defined max_val
if (val > max_val):
max_val = val
max_val_key = key
Upvotes: 0
Reputation: 17794
You can use the function max
:
max(list1, key=lambda x: list(x.values()))
# {'fg': 1144441565}
Upvotes: 2