我是Python新手(也是编程)。Python:如何在for循环中交替键来修改字典值?
我想通过交替字典的键来修改for循环中的字典。我写了下面的代码,这是unsccessful,但是:
#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”从另一个字典中制作字典,但我不明白为什么它是有问题的,即使是这种情况。
感谢您的关注。期待您的建议。
我得到了我期望的结果,我明白我错过了什么。谢谢! – 2011-03-12 10:39:55
@miyazaki_tara:如果你喜欢这个答案最好,你应该接受它。 – martineau 2011-03-12 22:13:56