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

时间:2019-03-29 13:40:32

标签: python python-2.7 list dictionary

我有一个词典列表:

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)

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

您也可以通过使用一组已经“可见”的条目过滤阵列来做到这一点:

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'}