Updating values in weird list of dicts

喜夏-厌秋 提交于 2020-01-05 06:37:12

问题


I have the following data structure:

fields = [{'key': 'ADDRESS1', 'value': None}, {'key': 'ADDRESS2', 'value': None}]

Please note, the structure of this data is outside of my control. But I have to work with it.

How would I go about updating the value "key" the Object where the key "key" is equal to, say 'ADDRESS1', such that I would have the following after manipulation:

N.B. The update has to update the value based off of the key, not the index of the object - as this is loosely defined.

fields = [{'key': 'ADDRESS1', 'value': 'Some Address Value'}, {'key': 'ADDRESS2', 'value': None}]


回答1:


d_list = [{'key': 'ADDRESS1', 'value': None}, {'key': 'ADDRESS2', 'value': None}] 

for d in d_list:
    if d['key'] == 'ADDRESS1':
        d['value'] = 'Some Address Value'

>>> d_list

[{'key': 'ADDRESS1', 'value': 'Some Address Value'}, {'key': 'ADDRESS2', 'value': None}]

EDIT: removed list comp as per suggestion in comments




回答2:


Brian Joseph's approach works well if you only plan on changing one value. But if you want to make a lot of changes, you might get tired of writing a loop and conditional for each change. In that case you may be better off converting your data structure into an ordinary dict, making your changes to that, and converting back to a weird-list-of-dicts at the end.

d_list = [{'key': 'ADDRESS1', 'value': None}, {'key': 'ADDRESS2', 'value': None}]
d = {x["key"]: x["value"] for x in d_list}

d["ADDRESS1"] = 'Some Address Value'
d["new_key"] = "foo"

new_d_list = [{"key": k, "value": v} for k,v in d.items()]
print(new_d_list)

Result:

[{'key': 'ADDRESS1', 'value': 'Some Address Value'}, {'key': 'ADDRESS2', 'value': None}, {'key': 'new_key', 'value': 'foo'}]

(Final ordering of the dicts may vary when using a Python version lower than 3.6)



来源:https://stackoverflow.com/questions/58646468/updating-values-in-weird-list-of-dicts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!