简体   繁体   English

如何在Python字典中的迭代中打印当前循环号?

[英]How to print current loop number in an iteration over a dictionary in Python?

I have a dictionary 我有一本字典

>>>d = {"a":"apple", "c":"cat", "d":"dog"}

That dictionary should be printed to output in this particular format: 该字典应以以下特定格式输出:

1. apple
2. cat
3. dog

If I have to use list comprehension to do so, how would I go about getting it to also print the current iteration number ie 1 or 2 or 3 as per above output. 如果我必须使用列表推导来执行此操作,我该如何去使其也打印当前的迭代数,即按照上面的输出来打印1或2或3。

This is what I have so far and it just prints the dict values on newlines, but it is far from what I want. 这是我到目前为止所拥有的,它只是将dict值打印在换行符上,但远非我想要的。

>>>temp =  "\n".join( [d[i] for i in d] )
>>>print temp
  • Also, is it beneficial to use a generator instead of list comprehension here? 另外,在这里使用生成器而不是列表理解是否有好处?
  • Enviroment: Python 2.7 环境:Python 2.7
In [90]: for i,arr in enumerate(d.values(), 1):
   ....:     print i, arr
   ....:     
   ....:     

1 apple
2 cat
3 dog

Sorted by value: 按值排序:

print '\n'.join('{}. {}'.format(i, d[k]) for (i,k) in enumerate(sorted(d, key=d.get), 1))
1. apple
2. cat
3. dog

Sorted by key: 按键排序:

>>> print '\n'.join('{}. {}'.format(i, d[k]) for (i,k) in enumerate(sorted(d), 1))
1. apple
2. cat
3. dog

Unsorted (results will come out however dict feels like giving them) 未排序(结果将出来,但是dict感觉像是给了他们)

>>> print '\n'.join('{}. {}'.format(i, v) for (i,v) in enumerate(d.itervalues(), 1))
1. apple
2. cat
3. dog

Simple dictionary iteration code will do this. 简单的字典迭代代码将执行此操作。 See the string formatting as well to pint out the location exactly as requested. 请参阅字符串格式,以完全按照要求指定位置。

d = {"a":"apple", "c":"cat", "d":"dog"}

count=1
for k,v in d.iteritems():
   print "%s. %s" % (count, k)
   count +=1

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

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