更新奇怪的字典列表中的值 [英] Updating values in weird list of dicts
问题描述
我有以下数据结构:
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.
我将如何更新 value
key"Object
,其中 key
key"等于 >'ADDRESS1'
,这样我就可以在操作后得到以下内容:
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:
注意更新必须根据 key
更新值,而不是对象的索引 - 因为这是松散定义的.
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}]
推荐答案
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:根据评论中的建议删除列表组合
EDIT: removed list comp as per suggestion in comments
这篇关于更新奇怪的字典列表中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!