Python 查找顶级字典值

Python 查找顶级字典值,python,dictionary,counter,Python,Dictionary,Counter,我收集了3本字典(城市、次国家、国家) 我需要一个函数,它将为我提供这些字典的n个顶级结果 到目前为止,我的代码只给出每个参数的顶部,而不是参数中定义的前3或前n def top_items(item_counts, n=3): d = collections.Counter(item_counts) d.most_common() for k, v in d.most_common(n): return (k, v) 我只尝试了d=计数器(item_c

我收集了3本字典(城市、次国家、国家)

我需要一个函数,它将为我提供这些字典的n个顶级结果

到目前为止,我的代码只给出每个参数的顶部,而不是参数中定义的前3或前n

def top_items(item_counts, n=3):
    d = collections.Counter(item_counts)
    d.most_common()
    for k, v in d.most_common(n):
        return (k, v)
我只尝试了d=计数器(item_counts),但它给出了未定义的错误计数器。我还导入了re和集合

我想跑

print('top cities:', top_items(cities))
print('top states:', top_items(subcountries))
print('top countries:', top_items(countries))
但是得到

top cities: ('', 665)
top states: ('', 552)
top countries: ('', 502)

for循环中的return语句导致函数在循环的第一次迭代中终止。如果您想返回n个最常见的项目,只需编写

def top_items(items, n=3):
   counts = collections.Counter(items)
   return counts.most_common(n)

您能给出输入和预期输出吗?谢谢@Jonatan!一个奇怪的问题。如果我只想返回键而不是值,那么我不会想到如何分割列表。ie您的代码给出:[(洛杉矶,15),(丹佛,10),(西雅图,5)],您如何只返回城市,而不是计数。谢谢您可以将其转换为dict,然后检索dict的键,或者使用列表/映射。因此
dict(counts.most_common(n)).keys()
[t[0]表示t in counts.most_common(n)]
这也会起作用:
下一步(zip(*counts.most_common(n))