python - 使用列表理解修改字典列表

标签 python dictionary

所以我有以下字典列表

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/

相关文章:

python - Scrapy:多个 "start_urls"产生重复的结果

python - 如何从命令行 python 获取列表作为输入?

python - 从排序的单词列表中高效打印匹配的 semordnilaps 对

python - 从嵌套字典中获取具有最大值的键

java - 如何使用java在mongoDB中保存和读取 map

python - 合并(连接)带有缺失值和不同类型(str & int)的 Pandas 列

python - 如何在 Flask-login 中调用 is_authenticated

ios - [iOS][后台]更新 map 图钉 |画线

c# - 在 C# 中测试对象是否为字典

javascript - 如何从 openlayers 6 中 map 的 postcompose 事件获取 Canvas