【发布时间】:2011-07-14 00:02:41
【问题描述】:
我是 Python 新手(和编程)。
我想通过交替字典的键来修改 for 循环中的字典。我写了以下代码,但是失败了:
#coding: utf-8
dict1 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
dict2 = dict.fromkeys(dict1.values(),[])
for key in dict2:
if key == 'value1':
dict2[key].extend(['test1', 'test2'])
elif key == 'value2':
dict2[key].extend(['test3', 'test4'])
elif key == 'value3':
dict2[key].extend(['test5', 'test6'])
print (dict2['value1'])
print (dict2['value3'])
我预计结果是:
['test5', 'test6']
['test1', 'test2']
但我实际上得到了:
['test5', 'test6', 'test3', 'test4', 'test1', 'test2']
['test5', 'test6', 'test3', 'test4', 'test1', 'test2']
我猜这个问题可能来自我使用“dict.fromkeys”从另一个字典制作字典,但即使是这样,我也看不出它为什么会出现问题。
感谢您的关注。期待您的建议。
【问题讨论】:
标签: python loops dictionary for-loop key