简体   繁体   English

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

[英]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.

相关问题 如何递归修改嵌套字典的键和值? - How can I recursively modify the keys and values of a nested dictionary? 如何在 For 循环 Python 中按字典中的键获取值 - How to get Values by Keys in Dictionary in For loop Python 如何反转 python 中字典中的键和值? - How can I reverse both keys and values in a dictionary in python? 如何通过交替数学运算在 python 上使用 for 循环? - How can I use a for loop on python with alternating mathematical operations? 在Python中创建一个带循环的交替字典 - Creating an alternating dictionary with a loop in Python 如何修改和删除Python2字典键中的特殊字符 - How can I modify and remove special characters in keys of Python2 dictionary 如何在python中获取一组交替值? - How can I get an array of alternating values in python? 如何使用for循环和带用户输入的if语句在python字典中的键/值之间循环? - How do I cycle through keys/values in a python dictionary using a for loop and if statement with user input? 如何根据 python 中另一个字典键的匹配来修改字典中的键值列表? - How to modify a list of key values in dictionary based on matches of another dictionary keys in python? 如何使用 while 循环从用户输入中附加具有任意数量的键和多个值的字典 - How can I use a while loop to append a dictionary with an arbitrary number of keys and multiple values from user inputs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM