所以我有以下字典列表
myList = [{'one':1, 'two':2,'three':3},
{'one':4, 'two':5,'three':6},
{'one':7, 'two':8,'three':9}]
这只是我拥有的字典的一个例子。我的问题是,有可能以某种方式修改 say key two
在所有字典中成为其值(value)的两倍,使用列表推导 ?
我知道如何使用列表理解来创建新的字典列表,但不知道如何修改它们,我想出了这样的东西
new_list = { <some if condiftion> for (k,v) in x.iteritems() for x in myList }
我不确定如何在 <some if condiftion>
中指定条件,我认为的嵌套列表理解格式也是正确的吗?
我想要像这样的示例的最终输出
[ {'one':1, 'two':4,'three':3},{'one':4, 'two':10,'three':6},{'one':7, 'two':16,'three':9} ]
最佳答案
将列表理解与嵌套字典理解结合使用:
new_list = [{ k: v * 2 if k == 'two' else v for k,v in x.items()} for x in myList]
print (new_list)
[{'one': 1, 'two': 4, 'three': 3},
{'one': 4, 'two': 10, 'three': 6},
{'one': 7, 'two': 16, 'three': 9}]
关于python - 使用列表理解修改字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51115660/