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 cont
Solution 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
Solution 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"] forxin d_list}
d["ADDRESS1"] = 'Some Address Value'
d["new_key"] = "foo"
new_d_list = [{"key": k, "value": v} fork,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)
Post a Comment for "Updating Values In Weird List Of Dicts"