collections.defaultdict() 与 dict的使用和区别

import collections
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]


# defaultdict
d = collections.defaultdict(list)
for k, v in s:
    d[k].append(v)


# Use dict and setdefault    
g = {}
for k, v in s:
    g.setdefault(k, []).append(v)
    
# Use dict
e = {}
for k, v in s:
    e[k] = v


print(d.items())
print(g.items())

print(e.items())


[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
[('blue', 4), ('red', 1), ('yellow', 3)]


你可能感兴趣的:(collections.defaultdict() 与 dict的使用和区别)