remove duplicates from nested dictionaries in list

前端 未结 6 1902
逝去的感伤
逝去的感伤 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:54

    In Python 2.6 or 3.*:

    import itertools
    import pprint
    
    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"}]
    
    getvals = operator.itemgetter('value3', 'value4')
    
    L.sort(key=getvals)
    
    result = []
    for k, g in itertools.groupby(L, getvals):
        result.append(g.next())
    
    L[:] = result
    pprint.pprint(L)
    

    Almost the same in Python 2.5, except you have to use g.next() instead of next(g) in the append.

提交回复
热议问题