简体   繁体   English

Python:如何从字典中获取最高键,一旦找到就获取键/值?

[英]Python : How to get the highest key from dictionary and once it found get the key/value?

hey guys I have a dictionary shows:嘿伙计们,我有一本字典显示:

Shows = {177.17: ['SELECT * FROM `breaking.bad` '], 190.16: ['SELECT * FROM `breaking.bad`'], 81.72: ['SELECT * FROM `mad.men`'], 74.36: ['SELECT * FROM `game.of.thrones`'], 74.37: ['SELECT * FROM `game.of.thrones`']}

here I have a list I want to match if those keys values occur:在这里,如果出现这些键值,我想匹配一个列表:

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

Currently what i want to achieve is once the list value matches with the list in the dictionary I get the highest value of those keys along with its value.目前我想要实现的是,一旦列表值与字典中的列表匹配,我就会得到这些键的最高值及其值。

What I have done so far is this:到目前为止我所做的是:

for key ,value in Shows.items():
    for lst in list:
        if lst in value and 'breaking.bad' in value and max(key) :
            print(lst)

Any ideas that can help achieve my goals?有什么想法可以帮助实现我的目标吗?

Not the most efficient way, but loop over the "tables" first, then get the dictionary for each show and find the max不是最有效的方法,但首先遍历“表”,然后获取每个节目的字典并找到最大值

shows = {177.17: ['SELECT * FROM `breaking.bad` '], 190.16: ['SELECT * FROM `breaking.bad`'], 81.72: ['SELECT * FROM `mad.men`'], 74.36: ['SELECT * FROM `game.of.thrones`'], 74.37: ['SELECT * FROM `game.of.thrones`']}
tables = ['breaking.bad','mad.men','game.of.thrones','the.mandalorian']


for table in tables:  # don't name variables as list
    sub_shows = {key:value for key,value in shows.items() if any(table in v for v in value)}
    if sub_shows:  # max throws error if list is empty
        print(max(sub_shows), table)

Output Output

190.16 breaking.bad
81.72 mad.men
74.37 game.of.thrones

I question the use-case of having a list of only one item, or why you need SQL queries in your dictionary我质疑只有一个项目的列表的用例,或者为什么你需要在字典中查询 SQL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM