python - 从字典中删除条目
问题描述
假设我有一本包含很多条目的字典,但我只需要打印前 5-10 个条目,我该怎么做呢?我考虑过使用 for 循环,但我找不到一种方法来使用字典,因为据我所知,你无法在不知道键名的情况下访问字典值。我还尝试将字典转换为元组列表,但这会导致条目的顺序以不需要的方式更改。有小费吗?
解决方案
对于字典 d,打印前 n 个值:
print(list(d.values())[:n])
如果字典表示单词的数量并且您想要前 n 个单词的列表:
d = {'red': 4, 'blue': 2, 'yellow': 1, "green":5} # Example dictionary
sorted_d = sorted(d.items(), key = lambda kv: -kv[1]) # Sort descending
n = 2 # number of values wanted
print(sorted_d[:n]) # list of top n tuples
# Out: [('green', 5), ('red', 4)]
您可以将单词和计数作为单独的列表
words, counts = zip(*sorted_d) # split into words and values
print(counts[:n]) # counts of top n words
# Out: (5, 4) # top n values
另一种选择是将字典转换为计数器
from collections import Counter
c = Counter(d)
print(c.most_common(n)) # Shows the n most common items in dictionary
# Out: {'green': 5, 'red': 4}
如果使用计数器,您还可以使用计数器来计算单词,如Counting words with Python's Counter中所述
推荐阅读
- javascript - 不知道为什么 CSS 选择器不起作用
- .net - 正则表达式在线查找最后一个单词(包括符号)
- google-apps-script - 谷歌工作表数据透视表 - 按来自不同字段的不同行分组
- swift - 从 UIViewController 向 UIView 发送数据
- jwt - 在 Swagger UI 中,如何从“匿名”方法中删除挂锁图标?
- php - 写入文件在functions.php中不起作用 - Wordpress
- python - 插入几个小时的条件
- c# - 在python中实现c#解密客户端的问题
- jquery - 如何使用类在 div 中使用输入的值
- ecmascript-6 - 如何在 ESM 中导入 UMD?