Python 2.7 按升序排序嵌套字典并获取外键?
我有一本字典,看起来像:Python 2.7 按升序排序嵌套字典并获取外键?,python-2.7,Python 2.7,我有一本字典,看起来像: dictionary = {'article1.txt': {'harry': 3, 'hermione': 2, 'ron': 1}, 'article2.txt': {'dumbledore': 1, 'hermione': 3}, 'article3.txt': {'harry': 5}} 我想选一篇赫敏出现次数最多的文章。我已经有了选择外键(article1.txt,article2.txt)和内键hermine)的代码 现在,我希望能够有代码将字典排序
dictionary = {'article1.txt': {'harry': 3, 'hermione': 2, 'ron': 1},
'article2.txt': {'dumbledore': 1, 'hermione': 3},
'article3.txt': {'harry': 5}}
我想选一篇赫敏出现次数最多的文章。我已经有了选择外键(article1.txt
,article2.txt
)和内键hermine
)的代码
现在,我希望能够有代码将字典排序为一个升序列表,以显示单词hermine
的最高出现次数。在本例中,我需要一个这样的列表['article1.txt','article2.txt']
。我使用以下代码进行了尝试:
#these keys are generated from another part of the program
keys1 = ['article1.txt', 'article2.txt']
keys2 = ['hermione', 'hermione']
place = 0
for i in range(len(keys1)-1):
for j in range(len(keys2)-1):
if articles[keys1[i]][keys2[j]] > articles[keys1[i+1]][keys2[j+1]]:
ordered_articles.append(keys1[i])
place += 1
else:
ordered_articles.append(place, keys1[i])
但是很明显(我现在意识到)遍历键来检查dictionary[key]>dictionary[next\u key]
是没有意义的。这是因为我们永远无法比较没有顺序的东西,比如dictionary[key[1]]>dictionary[key[3]]
非常感谢您的帮助 看来你要做的是按照文章中“赫敏”的数量对文章进行排序。而且,python有一个内置函数,可以完全做到这一点(您可以检查它)。你可以用它来根据每个单词所指向的赫敏的数量对字典键进行排序 下面是一段代码,您可以将其用作示例:
# filters out articles without hermione from the dictionary
# value here is the inner dict (for example: {'harry': 5})
dictionary = {key: value for key, value in dictionary.items() if 'hermione' in value}
# this function just returns the amount of hermiones in an article
# it will be used for sorting
def hermione_count(key):
return dictionary[key]['hermione']
# dictionary.keys() is a list of the keys of the dictionary (the articles)
# key=... here means we use hermione_count as the function to sort the list
article_list = sorted(dictionary.keys(), key=hermione_count)
谢谢有没有办法不必定义函数
hermione\u count(key)
?上下文:我可能会在代码中找到不止一个单词(即['hermine','dumbledore')。我认为排序(字典,key)
会起作用,但我不太确定在键中加入什么其他函数
你的意思是,你想把“赫敏”和“邓布利多”的数量加在一起吗?比如{“赫敏”:1,“邓布利多”:2}等于3?如果是这样的话,那么你可以简单地使用:dictionary[key][“赫敏”]+dictionary[key][“邓布利多”]路易斯:是的,这就是我想要的。我会在定义的函数中使用它作为返回吗?