gpt4 book ai didi

python - 迭代 defaultdict 字典的键和值

转载 作者:IT老高 更新时间:2023-10-28 21:53:00 28 4
gpt4 key购买 nike

以下按预期工作:

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 - 迭代 defaultdict 字典的键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2768188/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com