gpt4 book ai didi

python - 从具有重复键的字典列表中创建具有唯一键的字典列表

转载 作者:行者123 更新时间:2023-11-30 21:56:54 25 4
gpt4 key购买 nike

我有一个字典列表:

records = [{id:123, name:'Course A', enrolled_date:'1st Feb'}, 
{id:123, name:'Course A', enrolled_date:'1st Jan'},
{id:456, name:'Course B', enrolled_date:'1st Jan'}]

我想根据这些数据创建一个新的词典列表。新列表应仅包含在该列表范围内具有唯一 ids 的字典,例如:

new_records = [{id:123, name:'Course A'}, 
{id:456, name:'Course B'}]

这是我到目前为止尝试过的代码。这显然不起作用 - 但我已尽一切努力来纠正它。

new_records = []

for record in records:
new_id = record['id']
new_name = record['name']
new_dict = {'id':new_id, 'name',new_name}
If new_id not in new_records:
new_records.append(new_dict)

最佳答案

这是基于您提供的代码,但对于大型列表来说,它的运行速度非常慢,如其他评论中所述。

new_records = []

for record in records:
new_id = record['id']
new_name = record['name']
new_dict = {'id':new_id, 'name': new_name}
if not any(new_record['id'] == new_id for new_record in new_records):
new_records.append(new_dict)

关于python - 从具有重复键的字典列表中创建具有唯一键的字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55418748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com