remove duplicates from nested dictionaries in list

前端 未结 6 1886
逝去的感伤
逝去的感伤 2021-02-06 16:13

quick and very basic newbie question.

If i have list of dictionaries looking like this:

L = []
L.append({\"value1\": value1, \"value2\": value2, \"value3         


        
6条回答
  •  北荒
    北荒 (楼主)
    2021-02-06 16:49

    You can use a temporary array to store an items dict. The previous code was bugged for removing items in the for loop.

    (v,r) = ([],[])
    for i in l:
        if ('value4', i['value4']) not in v and ('value3', i['value3']) not in v:
            r.append(i)
        v.extend(i.items())
    l = r
    

    Your test:

    l = [{"value1": 'fssd', "value2": 'dsfds', "value3": 'abcd', "value4": 'gk'},
        {"value1": 'asdasd', "value2": 'asdas', "value3": 'dafdd', "value4": 'sdfsdf'},
        {"value1": 'sdfsf', "value2": 'sdfsdf', "value3": 'abcd', "value4": 'gk'},
        {"value1": 'asddas', "value2": 'asdsa', "value3": 'abcd', "value4": 'gk'},
        {"value1": 'asdasd', "value2": 'dskksks', "value3": 'ldlsld', "value4": 'sdlsld'}]
    

    ouputs

    {'value4': 'gk', 'value3': 'abcd', 'value2': 'dsfds', 'value1': 'fssd'}
    {'value4': 'sdfsdf', 'value3': 'dafdd', 'value2': 'asdas', 'value1': 'asdasd'}
    {'value4': 'sdlsld', 'value3': 'ldlsld', 'value2': 'dskksks', 'value1': 'asdasd'}
    

提交回复
热议问题