Remove duplicates key from list of dictionaries python

后端 未结 4 585
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-05 14:26

I am trying to remove the duplicates from following list

 distinct_cur = [{\'rtc\': 0, \'vf\': 0, \'mtc\': 0, \'doc\': \'good job\', \'foc\': 195, \'st\': 0         


        
4条回答
  •  没有蜡笔的小新
    2021-01-05 15:00

    You're creating a set out of different elements and expect that it will remove the duplicates based on a criterion that only you know.

    You have to iterate through your list, and add to the result list only if doc has a different value than the previous ones: for instance like this:

    done = set()
    result = []
    for d in distinct_cur:
        if d['doc'] not in done:
            done.add(d['doc'])  # note it down for further iterations
            result.append(d)
    

    that will keep only the first occurrence(s) of the dictionaries which have the same doc key by registering the known keys in an aux set.

    Another possibility is to use a dictionary with the key as the "doc" key of the dictionary, iterating backwards in the list so the first items overwrite the last ones in the list:

    result = {i['doc']:i for i in reversed(distinct_cur)}.values()
    

提交回复
热议问题