简体   繁体   English

更新奇怪的字典列表中的值

[英]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:我将如何 go 关于更新Objectvalue “键”,其中key “键”等于'ADDRESS1' ,这样我在操作后将拥有以下内容:

NB The update has to update the value based off of the key , not the index of the object - as this is loosely defined.注意更新必须根据key更新值,而不是 object 的索引 - 因为这是松散定义的。

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.如果您只计划更改一个值,Brian Joseph 的方法效果很好。 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) (使用低于 3.6 的 Python 版本时,dicts 的最终排序可能会有所不同)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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