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}]
添加回答
舉報