假设我有一个列表,例如
L = ['B0','B1','C1','C2','D1','D3']
然后,我如何将列表拆分为值和键,并以下列形式将其存储在字典中: -
{ 'B':['0','1'],
'C':['1','2'],
'D':['1','3']}
答案 0 :(得分:5)
L = ['B0','B1','C1','C2','D1','D3']
d = {}
for i in L:
d.setdefault(i[0], []).append(i[1])
>>> d
{'B': ['0', '1'], 'C': ['1', '2'], 'D': ['1', '3']}
答案 1 :(得分:5)
您可以遍历列表并中断每个字符串元素以创建字典。试试这个:
from collections import defaultdict
l = ['B0','B1','C1','C2','D1','D3']
d = defaultdict(list)
for key, value in l:
d[key].append(value)
print d