假设我有一个有很多词条的字典,但我只需要打印前5-10个词条,我该怎么做呢?我考虑过使用for循环,但我找不到一种方法来处理字典,因为据我所知,在不知道键名的情况下无法访问字典的值。我还尝试将字典转换为元组列表,但这会导致条目的顺序以不必要的方式更改。有什么建议吗?
发布于 2021-06-29 18:11:26
对于字典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所述
发布于 2021-06-29 18:02:51
如果asd是你的字典
asd = {'a':'1', 'b':'2', 'c':'3'}
for i, el in enumerate(asd.values()):
if i < 5:
print(el)这将打印前5个值,而不考虑键的名称。
https://stackoverflow.com/questions/68176474
复制相似问题