文章目录
目标
给定两个列表,将其合并到一个字典中
ids = ['a', 'b', 'a', 'c']
scores=[1, 2, 3, 4]
得到一个字典
ans={'a': [1, 3], 'b': [2],'c': [4]}
采用dict(zip(ids,scores))
时,会出现后面元素覆盖前面元素的情况
例如
>>> ids = ['a', 'b', 'a', 'c']
>>> scores=[1, 2, 3, 4]
>>> ans=dict(zip(ids,scores))
>>> ans
{'a': 3, 'b': 2, 'c': 4}
正解
当scores里面是单个元素
时,使用append()
方法
>>> ans={}
>>> ids = ['a', 'b', 'a', 'c']
>>> scores = [1, 2, 3, 4]
>>> for i, id in enumerate(ids):
if id not in ans.keys():
ans[id] = []
ans[id].append(scores[i])
>>> ans
{'a': [1, 3], 'b': [2], 'c': [4]}
当scores里面是列表
时,使用extend()
方法
>>> ans={}
>>> ids = ['a', 'b', 'a', 'c']
>>> scores = [[1], [2], [3], [4]]
>>> for i, id in enumerate(ids):
if id not in ans.keys():
ans[id] = []
ans[id].extend(scores[i])
>>> ans
{'a': [1, 3], 'b': [2], 'c': [4]}
进阶-defaultdict
from collections import defaultdict
ids = ['a', 'b', 'a', 'd']
scores = [1, 2, 3, 4]
id_score=zip(ids,scores)
d = defaultdict(list)
for k, v in id_score:
d[k].append(v)
>>> d.items()
dict_items([('a', [1, 3]), ('b', [2]), ('d', [4])])
from collections import defaultdict
ids = ['a', 'b', 'a', 'd']
scores = [1, 2, 3, 4]
id_score=zip(ids,scores)
d={}
for k,v in id_score:
d.setdefault(k,[]).append(v)
>>> d
{'a': [1, 3], 'b': [2], 'd': [4]}