[英]Find key value in list of dictionaries, and then replace the other values
I'm using Python and a JSON file containing a list of dictionaries like so:我正在使用 Python 和 JSON 文件,其中包含如下字典列表:
[
{'name':'person1','id':'123','status':'absent'},
{'name':'person2','id':'0980','status':'away'},
{'name':'person3','id':'5235','status':'present'}
]
And I have an incoming dictionary with the same format:我有一个格式相同的传入字典:
{'name':'person1','id':'324','status':'present'}
The incoming dictionary can have one thing in common, and that's the name
key, if the value for the 'name' key hasn't been seen, I add it the json
file, if it has, I update the values for the id
and status
keys in the json
file.传入的字典可能有一个共同点,那就是name
键,如果没有看到“名称”键的值,我将它添加到json
文件中,如果有,我更新id
和json
文件中的status
键。 I'm having trouble updating the list of dictionaries in the json
file.我在更新json
文件中的字典列表时遇到问题。
Taking the examples I gave above, the resulting json
file should look like this:以我上面给出的示例为例,生成的json
文件应如下所示:
[
{'name':'person1','id':'324','status':'present'},
{'name':'person2','id':'0980','status':'away'},
{'name':'person3','id':'5235','status':'present'}
]
I can manage to find the dictionary I want to change with the following:我可以通过以下方式找到我想要更改的字典:
dict_to_update = next(item for item in <jsonfilename> if item['name'] == 'desired name')
After this, I'm stuck trying to figure out how to then update the specific dictionary in the json
file.在此之后,我一直试图弄清楚如何更新json
文件中的特定字典。 Any ideas?有任何想法吗? Thank you.谢谢你。
Here is how:方法如下:
with open('file.json', 'r') as r:
lst = json.load(r)
for i,d in enumerate(lst):
if d['name'] == dct['name']:
lst[i] = dct
with open('file.json', 'w') as f:
json.dump(lst , f)
You can also use a function:您还可以使用 function:
def update(lst):
for i,d in enumerate(lst):
if d['name'] == dct['name']:
lst[i] = dct
return lst
with open('file.json', 'r') as r:
lst = update(json.load(r))
with open('file.json', 'w') as f:
json.dump(lst , f)
list_of_dict = [
{"name": "person1", "id": "123", "status": "absent"},
{"name": "person2", "id": "0980", "status": "away"},
{"name": "person3", "id": "5235", "status": "present"},
]
incoming_dictionary = {"name": "person1", "id": "324", "status": "present"}
for index, dictionary in enumerate(list_of_dict):
if incoming_dictionary["name"] == dictionary["name"]:
list_of_dict[
index
] = incoming_dictionary # replace the dictionary with the new one
break
else:
# if no match was found then append the incoming dictionary
list_of_dict.append(incoming_dictionary)
Here's a function that does so, maybe not as elegantly as other answers:这是一个 function 这样做,可能不像其他答案那样优雅:
def process(new_dict):
global data #jsonfilename
if new_dict['name'] in [d['name'] for d in data]:
data = [d for d in data if d['name'] != new_dict['name']]
data.append(new_dict)
data = sorted(data, key=lambda i: i['name'])
Full example:完整示例:
data = [{'name':'person1','id':'123','status':'absent'},
{'name':'person2','id':'0980','status':'away'},
{'name':'person3','id':'5235','status':'present'}]
process({'name':'person1','id':'324','status':'present'}) #an overwritten person
process({'name':'person4','id':'324','status':'present'}) #a new person
Result:结果:
[{'name': 'person1', 'id': '324', 'status': 'present'},
{'name': 'person2', 'id': '0980', 'status': 'away'},
{'name': 'person3', 'id': '5235', 'status': 'present'},
{'name': 'person4', 'id': '324', 'status': 'present'}]
You can do this while avoiding the global
keyword as well, but I thought this seemed alright for modifying an existing structure in place.您也可以在避免使用global
关键字的同时执行此操作,但我认为这对于修改现有结构似乎没问题。
Maybe this can help you, and if you found another short solution please let me know.也许这可以帮助您,如果您找到另一个简短的解决方案,请告诉我。 I make an iteration for the list of dictionary, and add a conditional to change the value of key id and status.我对字典列表进行了迭代,并添加了一个条件来更改键 id 和状态的值。 Another way is we can use filter and map, to have a short code instead.另一种方法是我们可以使用过滤器和 map 来代替短代码。
datas = [{'name': 'person1', 'id': '123', 'status': 'absent'}, {'name': 'person2', 'id': '0980',
'status': 'away'}, {'name': 'person3', 'id': '5235', 'status': 'present'}]
newData = {'name':'person1','id':'324','status':'present'}
for data in datas:
if data["name"]==newData["name"]:
data["id"]=newData["id"]
data["status"]=newData["status"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.