Python:如何在for循环交替键中修改字典值?

miy*_*ara 3 python dictionary loops for-loop key

我是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'])
Run Code Online (Sandbox Code Playgroud)

我预计结果是:

 ['test5', 'test6']
 ['test1', 'test2']
Run Code Online (Sandbox Code Playgroud)

但我实际上得到了:

 ['test5', 'test6', 'test3', 'test4', 'test1', 'test2']
 ['test5', 'test6', 'test3', 'test4', 'test1', 'test2']
Run Code Online (Sandbox Code Playgroud)

我想这个问题可能来自我使用"dict.fromkeys"另一个词典编纂词典,但我不明白为什么它是有问题的,即使是这样的.

感谢您的关注.期待您的建议.

Sve*_*ach 6

所有值dict2实际上都是相同的列表实例,因为传递[]dict.fromkeys()只创建一个列表实例.尝试

dict2 = dict((v, []) for v in dict1.values())
Run Code Online (Sandbox Code Playgroud)