所以我有以下字典列表
myList = [{'one':1, 'two':2,'three':3},
{'one':4, 'two':5,'three':6},
{'one':7, 'two':8,'three':9}]
Run Code Online (Sandbox Code Playgroud)
这只是我拥有的字典的一个例子。我的问题是,是否可以使用列表理解以某种方式修改two所有字典中的say 键,使其成为其值的两倍?
我知道如何使用列表理解来创建新的字典列表,但不知道如何修改它们,我想出了这样的东西
new_list = { <some if condiftion> for (k,v) in x.iteritems() for x in myList }
Run Code Online (Sandbox Code Playgroud)
我不确定如何在 中指定条件,<some if condiftion>我想的嵌套列表理解格式是否正确?
我想要像这样的示例那样的最终输出
[ {'one':1, 'two':4,'three':3},{'one':4, 'two':10,'three':6},{'one':7, 'two':16,'three':9} ]
Run Code Online (Sandbox Code Playgroud)
使用嵌套字典理解的列表理解:
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}]
Run Code Online (Sandbox Code Playgroud)