简体   繁体   中英

python : How to get the max value of dictionary keys in list of dictionaries

Hello everyone lets say I have a list of values

shows = ['breaking.bad','mad.men','game.of.thrones','the.mandalorian']

I created a dictionary

d = defaultdict(list)


weekly_ratings = {
    5.0 : 'breaking.bad',
    4.0 : 'mad.men',
    4.6 : 'game.of.thrones',
    4.7 : 'the.mandalorian',
    2.5 : 'breaking.bad',
    3.5 : 'mad.men'
}

    for show in shows:
        for key, value in weekly_ratings.items():
            if any(show in v for v in value):
                d[show].append({key : value})
    new_d = dict(d)
    print(new_d)
    print(new_d['breaking.bad'])

this is my response for new_d

 {'breaking.bad': [{5.0: ('breaking.bad')}, {4.5: ('breaking.bad')}], 'mad.men': [{4.0: ('mad.men')}, {3.0: ('mad.men')}], 'game.of.thrones': [{4.5: ('game.of.thrones')}], 'the.mandalorian': [{4.0: ('the.mandalorian')}]}

here is the response I get for specific field for example breaking bad :

[{5.0: ('breaking.bad')}, {4.5 : ('breaking.bad')}]

what i want to achieve is to get the highest key of a specific field in the list of dictionaries in new_d

the expected output of a specific field(in this case breaking bad) : 5.0

I have already tried print(new_d['breaking.bad'][0][new_d.keys()])

but i get the error:

TypeError: 'dict_keys' object is not subscriptable

Any pro tips or advice on how I can solve this issue?

Going from OP's comment: "i do know of the max function but If im looking for a specific field like breaking bad how to I get the max key of that field?"

If you want to get the maximum key with a particular value, you can use max with a generator expression, like this:

max(k for (k,v) in weekly_ratings.items() if v=='breaking.bad') 

Using itertools.groupby

from itertools import groupby

data = sorted(weekly_ratings.items(), key=lambda x: x[1])
res = {k: max(g)[0] for k, g in groupby(data, key=lambda x: x[1])}
print(res)

Output:

{'breaking.bad': 5.0, 'game.of.thrones': 4.6, 'mad.men': 4.0, 'the.mandalorian': 4.7}

Using dict comprehension

res = {k: list(max(v, key=max).keys())[0] for k, v in new_d.items()}

print(res)

Output:

{'breaking.bad': 5.0, 'mad.men': 4.0, 'game.of.thrones': 4.5, 'the.mandalorian': 4.0}

To begin with, your dictionary must be set up the other way around, so the key would be the description while your value would be the weekly rating. Once you have the dictionary set up in this way, you get the key (description) with the maximum value (value) as:

max_rating_key = max(weekly_ratings, key=weekly_ratings.get)

If you still need to know the actual value just do:

max_rating = weekly_ratings[max_rating_key]

By the way, you can not have two values for a key in a dictionary as would be with the way you presented the data. Good luck

Try using max() function. I assume you want only the ratings value, right? You can use something like this:

x = max(weekly_ratings.keys())
print(x)

The keys() function will get the value of the key.

This sort of thing is much easier using set operations. The following shows how it can be done with Pandas.

import pandas as pd
import pandasql as ps

shows = ['breaking.bad','mad.men','game.of.thrones','the.mandalorian']

df_shows = pd.DataFrame({'title': shows})

df_ratings = pd.DataFrame( 
 [['breaking.bad',   5.0 ],
 ['mad.men',         4.0 ],
 ['game.of.thrones',     4.5 ],
 ['the.mandalorian',     4.0 ],
 ['breaking.bad',    4.5 ],
 ['mad.men' ,    3.5 ]], columns = ['title', 'rating'])  


top_rating_by_movie = ps.sqldf("""
    select  dfs.title, max(dfr.rating)  max_rating
    from df_shows dfs
     left join df_ratings dfr
      on dfr.title = dfs.title
    group by 1  """, locals())

print(top_rating_by_movie)

which results in the following:

             title  max_rating
0     breaking.bad         5.0
1  game.of.thrones         4.5
2          mad.men         4.0
3  the.mandalorian         4.0

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