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

我有一个字典列表:


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)


慕森卡
浏览 135回答 2
2回答

翻阅古今

这是基于您提供的代码,但如其他评论中所述,对于大列表,它的工作速度真的很慢。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)

莫回无

您还可以通过使用一组已经“见过”的条目过滤数组来实现: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'}]seen     = set()new_dict = [d for d in records if not(d['id'] in seen or seen.add(d['id']))]# {'id': 123, 'name': 'Course A', 'enrolled_date': '1st Feb'}# {'id': 456, 'name': 'Course B', 'enrolled_date': '1st Jan'}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python