我有一个哈希列表:
[
{'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}
)?
答案 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()