Merging repeated items in a list into a python dictionary

前端 未结 2 669
难免孤独
难免孤独 2021-01-14 23:13

I have a list that looks like the one bellow, with the same item of a pair repeated some times.

l = ([\'aaron distilled \', \'alcohol\', \'5\'], 
[\'aaron di         


        
2条回答
  •  忘掉有多难
    2021-01-14 23:46

    Use a collections.defaultdict() object for ease:

    from collections import defaultdict
    
    result = defaultdict(list)
    
    for key, *values in data:
        result[key].extend(values)
    

    Your first attempty will overwrite keys; a dict comprehension would not merge the values. The second attempt seems to treat the lists in the data list as dictonaries, so that wouldn't work at all.

    Demo:

    >>> from collections import defaultdict
    >>> data = (['aaron distilled ', 'alcohol', '5'], 
    ... ['aaron distilled ', 'gin', '2'], 
    ... ['aaron distilled ', 'beer', '6'], 
    ... ['aaron distilled ', 'vodka', '9'], 
    ... ['aaron evicted ', 'owner', '1'], 
    ... ['aaron evicted ', 'bum', '1'], 
    ... ['aaron evicted ', 'deadbeat', '1'])
    >>> result = defaultdict(list)
    >>> for key, *values in data:
    ...    result[key].extend(values)
    ... 
    >>> result
    defaultdict(, {'aaron distilled ': ['alcohol', '5', 'gin', '2', 'beer', '6', 'vodka', '9'], 'aaron evicted ': ['owner', '1', 'bum', '1', 'deadbeat', '1']})
    

提交回复
热议问题