簡體   English   中英

遍歷defaultdict字典的鍵和值

[英]Iterating over key and value of defaultdict dictionaries

預期的工作如下:

d = [(1,2), (3,4)]
for k,v in d:
  print "%s - %s" % (str(k), str(v))

但這失敗了:

d = collections.defaultdict(int)
d[1] = 2
d[3] = 4
for k,v in d:
  print "%s - %s" % (str(k), str(v))

帶有:

Traceback (most recent call last):  
 File "<stdin>", line 1, in <module>  
TypeError: 'int' object is not iterable 

為什么? 我該如何解決?

您需要遍歷dict.iteritems()

for k,v in d.iteritems():               # will become d.items() in py3k
  print "%s - %s" % (str(k), str(v))

更新:在py3 V3.6 +中

for k,v in d.items():
  print (f"{k} - {v}")

如果您使用的是Python 3.6

from collections import defaultdict

for k, v in d.items():
    print(f'{k} - {v}')

如果要遍歷單個集合中的單個項目:

from collections import defaultdict

for k, values in d.items():
    for value in values:
       print(f'{k} - {value}')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM