检查数组中是否存在元素哈希并更新它,否则插入它

时间:2015-03-18 05:52:59

标签: python

我有一个哈希列表:

[
  {'key1': 'value1', 'key2': some_object},
  {'key1': 'value21', 'key2': some_object2},
  {'key1': 'value133', 'key2': some_object3}
]

检查具有'key1': 'value133'的元素是否存在(如果我的情况确实存在)并更新它的最简单方法是什么(比如说'key1': 'value133', 'key2': some_object333}否则插入它({'key1': 'value133', 'key2': some_object3})?

1 个答案:

答案 0 :(得分:1)

l = [
  {'key1': 'value1', 'key2': 'some_object'},
  {'key1': 'value21', 'key2': 'some_object2'},
  {'key1': 'value133', 'key2': 'some_object3'}
]

d = any(d for d in l if d['key1'] == 'value133')
if  d:
    d['key2'] = 'some_object333'
else :
    l.append({'key1': 'value133', 'key2': 'some_object3'})

print(d)

使用any()

执行此类操作