3 回答
TA贡献1804条经验 获得超7个赞
将列表理解与dict嵌套嵌套一起使用:
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}]
TA贡献1911条经验 获得超7个赞
在python 3.5+中,您可以在PEP 448中引入的dict文字中使用新的解包语法。这将创建每个字典的副本,然后覆盖键的值two:
new_list = [{**d, 'two': d['two']*2} for d in myList]
# result:
# [{'one': 1, 'two': 4, 'three': 3},
# {'one': 4, 'two': 10, 'three': 6},
# {'one': 7, 'two': 16, 'three': 9}]
TA贡献1828条经验 获得超4个赞
一个简单的for循环就足够了。但是,如果要使用字典理解,我发现定义映射字典比三元语句更易读和可扩展:
factor = {'two': 2}
res = [{k: v*factor.get(k, 1) for k, v in d.items()} for d in myList]
print(res)
[{'one': 1, 'two': 4, 'three': 3},
{'one': 4, 'two': 10, 'three': 6},
{'one': 7, 'two': 16, 'three': 9}]
添加回答
举报