我正在尝试为下面的元组列表构建一个字典:
lst=[('ldb', 25), ('baseB', 4), ('code', 112),
('cache-6', 55), ('Xauthority', 1), ('baseA', 4),
('npmrc', 1), ('apmrc', 1),('gz', 190),
('dbf', 1), ('lst', 2), ('markdown', 10),
('sqlite-shm', 2), ('vsixmanifest', 4), ('ttf', 109),
('pkl', 35), ('gitignore', 8), ('xml', 46)]
通过使用这样的连接:
op= {','.join( '\'%s\':%d'%i for i in lst)}
但输出op
的类型为set
,如下所示!!
set(["'ldb':25,'baseB':4,'code':112,'cache-6':55, 'Xauthority':1,'baseA':4,'npmrc':1,'apmrc':1,
'gz':190,'dbf':1,'lst':2,'markdown':10,'sqlite-shm':2,'vsixmanifest':4,'ttf':109,'pkl':35,'gitignore':8,'xml':46"])
有人纠正了我dictionary
而不是set
提前谢谢。
答案 0 :(得分:0)
目前,您正在创建一个集合,而不是字典。试试这个:
lst=[('ldb', 25), ('baseB', 4), ('code', 112), ('cache-6', 55), ('Xauthority', 1), ('baseA', 4), ('npmrc', 1), ('apmrc', 1), ('gz', 190), ('dbf', 1), ('lst', 2), ('markdown', 10), ('sqlite-shm', 2), ('vsixmanifest', 4), ('ttf', 109), ('pkl', 35), ('gitignore', 8), ('xml', 46)]
new_data = {a:b for a, b in lst}
或者,更好的是:
new_data = dict(lst)
答案 1 :(得分:0)
试一试:
lst = [('ldb', 25), ('baseB', 4), ('code', 112), ('cache-6', 55), ('Xauthority', 1), ('baseA', 4), ('npmrc', 1),
('apmrc', 1), ('gz', 190), ('dbf', 1), ('lst', 2), ('markdown', 10), ('sqlite-shm', 2), ('vsixmanifest', 4),
('ttf', 109), ('pkl', 35), ('gitignore', 8), ('xml', 46)]
d = dict()
for i in lst:
d[i[0]] = i[1]
print(d)