首页 > 解决方案 > 从字典中删除条目

问题描述

假设我有一本包含很多条目的字典,但我只需要打印前 5-10 个条目,我该怎么做呢?我考虑过使用 for 循环,但我找不到一种方法来使用字典,因为据我所知,你无法在不知道键名的情况下访问字典值。我还尝试将字典转换为元组列表,但这会导致条目的顺序以不需要的方式更改。有小费吗?

标签: python

解决方案


对于字典 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中所述


推荐阅读