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

时间:2019-10-31 15:17:15

标签: python python-3.7

我具有以下数据结构:

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

请注意,此数据的结构超出了我的控制范围。但是我必须使用它。

value“密钥”等于Object的情况下,我将如何更新key的{​​{1}}“密钥”,操作后,以下内容:

更新必须根据'ADDRESS1'而不是对象的索引来更新值-因为它的定义很松散。

key

2 个答案:

答案 0 :(得分:3)

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

编辑:根据评论中的建议删除了列表内容

答案 1 :(得分:2)

如果您仅计划更改一个值,那么布莱恩·约瑟夫的方法将非常有效。但是,如果您想进行很多更改,您可能会厌倦了为每个更改编写循环和有条件的操作。在这种情况下,最好将数据结构转换为普通字典,对其进行更改,最后再转换回奇怪的字典列表。

<source>:133:17: error: static_assert expression is not an integral constant expression
  static_assert(Miller(num, iteration));
                ^~~~~~~~~~~~~~~~~~~~~~
<source>:62:12: note: value 232307310937188460801 is outside the range of representable values of type 'long long'
    y = (y * y) % mod;
           ^
<source>:104:14: note: in call to 'modulo(123457, 63024450155, 252097800623)'
    ll mod = modulo(a, temp, p);
             ^
<source>:133:17: note: in call to 'Miller(252097800623, 5)'
  static_assert(Miller(num, iteration));

结果:

long long

(使用低于3.6的Python版本时,字典的最终顺序可能会有所不同)