简体   繁体   English

如何解决 python 中的 KeyError? 检查下面的代码

[英]How do i resolve a KeyError in python? check the code below

def myFUNC (e):
  return e["Points"]

team_stats = [
            {"76ers" : {"Wins" : 22,
                       "Losses" : 12,
                       "Points" : 647},
            "Nets" :  {"Wins" : 22,
                       "Losses" : 13,
                       "Points" : 629},
            "Bucks" :  {"Wins" : 21,
                       "Losses" : 13,
                       "Points" : 618}}
              ]
print(team_stats.sort(key=myFUNC))
KeyError: 'Points'

The reason you get KeyError is because you trying to access the key "Points" from the outer level of the dictionary, where it does not belong, and even if it did, with the current structure, you will see no difference in the result.你得到KeyError的原因是因为你试图从字典的外层访问键"Points" ,它不属于它,即使它这样做了,使用当前结构,你不会看到结果有什么不同。

You have a single dict inside a list , there is nothing to sort .您在list中只有一个dict ,没有要sort的内容。 If you want to sort the dict , that is only possible if you are using 3.7+ , because from 3.7 onwards, dict s in Python are guaranteed to maintain order .如果要对dict进行排序,则只有在使用3.7+时才有可能,因为从3.7开始, 保证 Python 中的dict保持 order If you do meet the version requirement, then use:如果您确实满足版本要求,请使用:

def myFUNC (e):
  return e[1]["Points"]

team_stats = [
            {"76ers" : {"Wins" : 22,
                       "Losses" : 12,
                       "Points" : 647},
            "Nets" :  {"Wins" : 22,
                       "Losses" : 13,
                       "Points" : 629},
            "Bucks" :  {"Wins" : 21,
                       "Losses" : 13,
                       "Points" : 618}}
              ]
result = [dict(sorted(team_stats[0].items(), key=myFUNC))]
print(result)

Which gives这使

[{'Bucks': {'Wins': 21, 'Losses': 13, 'Points': 618},
  'Nets': {'Wins': 22, 'Losses': 13, 'Points': 629},
  '76ers': {'Wins': 22, 'Losses': 12, 'Points': 647}}]

If you do not meet the version requirement, you need to use an collections.OrderedDict :如果不满足版本要求,则需要使用collections.OrderedDict

from collections import OrderedDict
# replace the `result` line with this:
result = [OrderedDict(sorted(team_stats[0].items(), key=myFUNC))]

Which gives:这使:

[OrderedDict([('Bucks', {'Wins': 21, 'Losses': 13, 'Points': 618}),
              ('Nets', {'Wins': 22, 'Losses': 13, 'Points': 629}),
              ('76ers', {'Wins': 22, 'Losses': 12, 'Points': 647})])]

But I don't see why you need the list here.但我不明白你为什么需要这里的列表。

Also, list().sort() modifies the list in-place, which not only is useless here, printing this will return None .此外, list().sort()就地修改list ,这不仅在这里没用,打印它还将返回None

I think what you meant is this maybe?我想你的意思是这可能吗?

def myFUNC (i):
  return i[1]["Points"]

team_stats =  {"76ers" : {"Wins" : 22,
                       "Losses" : 12,
                       "Points" : 647},
            "Nets" :  {"Wins" : 22,
                       "Losses" : 13,
                       "Points" : 629},
            "Bucks" :  {"Wins" : 21,
                       "Losses" : 13,
                       "Points" : 618}}

print(sorted(team_stats.items(), key=myFUNC))

You sort each name by the points.您按点对每个名称进行排序。

The problem is that you have a dictionary inside of list, so when you try to sort the list, it is looking at the outer dictionary, and not the inner ones.问题是您在列表中有一个字典,因此当您尝试对列表进行排序时,它正在查看外部字典,而不是内部字典。

A solution is to use just the dictionary items as follows:一种解决方案是仅使用字典项,如下所示:

team_stats =     {"76ers" : {"Wins" : 22,
                       "Losses" : 12,
                       "Points" : 647},
            "Nets" :  {"Wins" : 22,
                       "Losses" : 13,
                       "Points" : 629},
            "Bucks" :  {"Wins" : 21,
                       "Losses" : 13,
                       "Points" : 618}}
sorted_teams = list(team_stats.items())  
sorted_teams.sort(key = lambda team : team[1]["Points"])   
# [('Bucks', {'Wins': 21, 'Losses': 13, 'Points': 618}), ('Nets', {'Wins': 22, 'Losses': 13, 'Points': 629}), ('76ers', {'Wins': 22, 'Losses': 12, 'Points': 647})]

If you store your dict outside of a list, you can sort it quite simply.如果您将dict存储在列表之外,则可以非常简单地对其进行排序。

You can also keep your output as a dict by enclosing the sorted() method in dict()您还可以通过将sorted()方法包含在dict()中来将 output 保留为dict

team_stats =  {"76ers" : {"Wins" : 22,
                   "Losses" : 12,
                   "Points" : 647},
        "Nets" :  {"Wins" : 22,
                   "Losses" : 13,
                   "Points" : 629},
        "Bucks" :  {"Wins" : 21,
                   "Losses" : 13,
                   "Points" : 618}}

dict(sorted(team_stats.items(), key=lambda x: x[1]['Points']))

#{'Bucks': {'Wins': 21, 'Losses': 13, 'Points': 618}, 'Nets': {'Wins': 22, 'Losses': 13, 'Points': 629}, '76ers': {'Wins': 22, 'Losses': 12, 'Points': 647}}

# in reverse
dict(sorted(team_stats.items(), key=lambda x: x[1]['Points'], reverse=True))
#{'76ers': {'Wins': 22, 'Losses': 12, 'Points': 647}, 'Nets': {'Wins': 22, 'Losses': 13, 'Points': 629}, 'Bucks': {'Wins': 21, 'Losses': 13, 'Points': 618}}

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

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