[英]Python: How can I modify dictionary values in a for loop alternating the keys?
I am new to Python (and to programming).我是 Python 新手(和编程)。
I'd like to modify a dictionary in a for loop by alternating the key of the dictionary.我想通过交替字典的键来修改 for 循环中的字典。 I wrote the following code, which was unsccessful, however:我写了以下代码,但是没有成功:
#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'])
I expected the results to be:我预计结果是:
['test5', 'test6']
['test1', 'test2']
but I actually got:但我实际上得到了:
['test5', 'test6', 'test3', 'test4', 'test1', 'test2']
['test5', 'test6', 'test3', 'test4', 'test1', 'test2']
I guess the problem might come from my making the dictionary from another dictionary using "dict.fromkeys", but I couldn't see why it is problematic even if it is the case.我想问题可能来自我使用“dict.fromkeys”从另一个字典制作字典,但即使是这样,我也看不出为什么它是有问题的。
Thanks for your attention.感谢您的关注。 Looking forward to your suggestions.期待您的建议。
All values of dict2
are actually the same list instance, since passing []
to dict.fromkeys()
only creates one list instance. dict2
的所有值实际上都是同一个列表实例,因为将[]
传递给dict.fromkeys()
只会创建一个列表实例。 Try尝试
dict2 = {v: [] for v in dict1.values()}
The problem is you used a mutable object as the value initializer.问题是您使用可变对象作为值初始化程序。 It is the very same object for each value.对于每个值,它都是相同的对象。
Python2> dict1 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
Python2> dict2 = dict.fromkeys(dict1.values(),[])
Python2> dict2
{'value1': [], 'value2': [], 'value3': []}
Python2> dict2['value1']
[]
Python2> id(dict2['value1'])
43895336
Python2> id(dict2['value2'])
43895336
Python2> id(dict2['value3'])
43895336
So you are extending the same list.因此,您正在扩展相同的列表。
遍历yourdict.keys()
(这将返回一个列表,因此它不会受到对字典的任何更改的影响)
问题是dict.fromkeys()
使用相同的 object初始化每个项目。
dict2 = dict((x, []) for x in dict1.values())
As others have pointed-out, the problem is that your call to dict.fromkeys()
associates a reference to the same empty list with each key it creates in the new dictionary.正如其他人指出的那样,问题在于您对dict.fromkeys()
的调用会将对同一空列表的引用与它在新字典中创建的每个键相关联。 An easy solution is to make dict2
a defaultdict
class from the collections
module and make the default value a separate newly created empty list
:一个简单的解决方案是使dict2
成为collections
模块中的defaultdict
类,并使默认值成为一个单独的新创建的空list
:
from collections import defaultdict
dict1 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
dict2 = defaultdict(list)
for key in dict1.itervalues():
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']
# ['test1', 'test2']
print dict2['value3']
# ['test5', 'test6']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.