简体   繁体   English

遍历字典 X 次

[英]Iterating through a dictionary for X number of times

Assume the dictionary contains more than 10 key-value pairs.假设字典包含超过 10 个键值对。 The dictionary ought to be sorted by values (of integers).字典应该按值(整数)排序​​。 Print out the top 10 values (and corresponding keys).打印出前 10 个值(和相应的键)。 I think there is a better solution that what I have given here.我认为有一个更好的解决方案,我在这里给出的。

for keys in sorted(x):
   c=c+1
   if c>10:
      break
   else:
      print keys, x['keys']
for key in sorted(x, key=x.get, reverse=True)[:10]:
    print key, x[key]

For really large dict you should consider using a heapq对于非常大的dict您应该考虑使用 heapq

from heapq import nlargest
for key in nlargest(10, x, key=x.get):
    print key, x[key]

There is no order defined on dictionary keys, so the "first" keys are not well defined.字典键没有定义顺序,所以“第一个”键没有明确定义。 Specifically, what you did is easier done with x.keys()[:10] .具体来说,使用x.keys()[:10]可以更轻松地完成您所做的工作。

topten = sorted(x.items(), key=lambda x:-x[1])[:10]

You can iterate over dict for X number of times using the following code.您可以使用以下代码在dict迭代 X 次。

Python 3.8蟒蛇 3.8

def highest_contributor(self, top=1):
    slice_dict_only_to_keys = list(self.contributors.keys())[:top]
    for _key in slice_dict_only_to_keys:
        self.log("Top Contributor: {} ({})".format(_key, self.contributors[_key]))

Don't worry about integers and incrementing them with your code.不要担心整数并用您的代码增加它们。 You don't need them.你不需要它们。

Simple, readable and Maintainable.简单,可读和可维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM