您好,我有以下数据形式
fields = [{'name':'xxx', 'age':24, 'location':'city_name'},
{'name':'yyy', 'age':24, 'location':'city_name'}]
现在我想用两个dicts更新位置,并以相同的格式保存字段。怎么做?我是初学者。
答案 0 :(得分:1)
为两个字段设置相同的位置。
>>> fields = [{'name':'xxx', 'age':24, 'location':'city_name'},
... {'name':'yyy', 'age':24, 'location':'city_name'}]
>>> for field in fields:
... field['location'] = 'loc'
...
>>> fields
[{'age': 24, 'name': 'xxx', 'location': 'loc'}, {'age': 24, 'name': 'yyy', 'location': 'loc'}]
要设置不同的位置,请使用zip
:
>>> for field, loc in zip(fields, ['here', 'there']):
... field['location'] = loc
...
>>> fields
[{'age': 24, 'name': 'xxx', 'location': 'here'}, {'age': 24, 'name': 'yyy', 'location': 'there'}]