假如有需求,
data = [("p", 1), ("p", 2), ("p", 3),
("h", 1), ("h", 2), ("h", 3)]
要转换成
result = {'p': [1, 2, 3], 'h': [1, 2, 3]}
我的第一想法就是这么做
result = {}
for (key, value) in data:
if key in result:
result[key].append(value)
else:
result[key] = [value]
师傅看了之后笑了,扔来一段
result = {}
data = [("p", 1), ("p", 2), ("p", 3),
("h", 1), ("h", 2), ("h", 3)]
for (key, value) in data:
result.setdefault(key, []).append(value)
print(result)#'p': [1, 2, 3], 'h': [1, 2, 3]}
setderault()方法接收两个参数,用法和get类似,但比get强大,它可以给字典的key设定一个默认值(如果key不在字典中的时候),
defaultdict(list),会构建一个默认value为list的字典,
from collections import defaultdict
result = defaultdict(list)
data = [("p", 1), ("p", 2), ("p", 3),
("h", 1), ("h", 2), ("h", 3)]
for (key, value) in data:
result[key].append(value)
print(result)#defaultdict(, {'p': [1, 2, 3], 'h': [1, 2, 3]})