记录一下
python字典遍历错误
代码
dic = { 'a':1, 'b':2 } for key,value in dic: print(key+':'+ str(value))
输出:
ValueError: not enough values to unpack (expected 2, got 1)
这是因为“dic”字典中的每一个条目(item)都是一个值:键和值在字典中不是两个独立的值。
可以使用items()方法来解决这个错误。此方法分析字典并返回以元组存储的键和值:
items()
>>> print(dic.items()) dict_items([('a', 1), ('b', 2)])
原问题:
for key,value in dic.items(): # 在这里 print(key+':'+str(value))
结果:
a:1 b:2
Content: