from collections import defaultdict

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = collections.defaultdict(list)
for k, v in s:
    d[k].append(v)
>>输出d:defaultdict(list, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})


# Use dict and setdefault    
g = {}
for k, v in s:
    g.setdefault(k, []).append(v)
>>输出g:{'yellow': [1, 3], 'blue': [2, 4], 'red': [1]}


# Use dict
e = {}
for k, v in s:
    e[k] = v
>>输出e:{'yellow': 3, 'blue': 4, 'red': 1}

posted on 2021-04-13 16:07  jaysonteng  阅读(57)  评论(0编辑  收藏  举报