简体   繁体   中英

Updating values in weird list of dicts

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:

NB 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}]

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM