How to assign all values in dictionary to variables based on max value

Viewed 63

List contains dictionaries and their values are again list. How to print max value and country name from the values.

data = [{'country':[2,'US']},{'country':[1,'EN']}]

Example: In values 2 is maximum and the country is 'US' so it should print instead of another dictionary. I ran the code below but I didn't get the desired result on, how to be more efficient.

for i in data:
    for m,j in i.items():
        country = j[1][1]
        points = j[1][0]


Example Output:

points = 2
country = 'US'
2 Answers

try:

data = [{'country': [2, 'US']}, {'country': [1, 'EN']}]

max_dic = max(data, key=lambda x: x['country'][0])
points, country = max_dic['country']

print(country)
print(points)

The below seems to work

_max = (-1,None) # assuming max cant be negative
data = [{'country':[2,'US']},{'country':[1,'EN']}]
for entry in data:
    if entry['country'][0] > _max[0]:
        _max = tuple(entry['country'])
print(_max)

output

(2, 'US')
Related