我如何获得这样的字典:
{'SEA': {'SFO': 6.020797289396148, 'DEN': 12.041594578792296, 'OAK': 6.029925372672534}, 'SFO': {'SEA': 6.020797289396148, 'DEN': 9.7082439194738}}
是这样的:
[['SEA', ['SFO', 6.020797289396148, 'DEN', 12.041594578792296, 'OAK', 6.029925372672534]], ['SFO', ['SEA', 6.020797289396148, 'DEN', 9.7082439194738]]]
答案 0 :(得分:4)
将嵌套的dictionary comprehension
与zip
和dict
配合使用:
l = [['SEA', ['SFO', 6.020797289396148, 'DEN', 12.041594578792296, 'OAK', 6.029925372672534]], ['SFO', ['SEA', 6.020797289396148, 'DEN', 9.7082439194738]]]
d = {v[0]:{k:v1 for k,v1 in zip(v[1][::2], v[1][1::2])} for v in l}
或使用如下所示的for循环:
d = {}
for v in l:
temp_d = {}
for k,v1 in zip(v[1][::2],v[1][1::2]):
temp_d[k]=v1
d[v[0]]=temp_d
或者:
d = {v[0]:dict(zip(v[1][::2],v[1][1::2])) for v in l}
print(d)
{'SEA': {'SFO': 6.020797289396148,
'DEN': 12.041594578792296,
'OAK': 6.029925372672534},
'SFO': {'SEA': 6.020797289396148, 'DEN': 9.7082439194738}}
答案 1 :(得分:0)
您可以使用dict理解,
In [95]: {key:dict(zip(values[::2], values[1::2])) for key,values in a}
Out[95]:
{'SEA': {'DEN': 12.041594578792296,
'OAK': 6.029925372672534,
'SFO': 6.020797289396148},
'SFO': {'DEN': 9.7082439194738, 'SEA': 6.020797289396148}}
zip(values[::2], values[1::2])
将创建这样的元组列表,
[('SFO', 6.020797289396148),
('DEN', 12.041594578792296),
('OAK', 6.029925372672534)]
dict(zip(values[::2], values[1::2]))
将生成一个与此类似的字典,
{'DEN': 12.041594578792296,
'OAK': 6.029925372672534,
'SFO': 6.020797289396148}
答案 2 :(得分:0)
简单的方法
d = {'SEA': {'SFO': 6.020797289396148, 'DEN': 12.041594578792296, 'OAK': 6.029925372672534}, 'SFO': {'SEA': 6.020797289396148, 'DEN': 9.7082439194738}}
l = []
for a in d.keys():
l2 = []
d2 = d[a]
for b in d2.keys():
l2.extend([b,d2[b]])
l.extend([a,l2])
print(l)
你得到 ['SEA',['SFO',6.020797289396148,'DEN',12.041594578792296,'OAK',6.029925372672534],'SFO',['SEA',6.020797289396148,'DEN',9.7082439194738]]
答案 3 :(得分:0)
[['SEA', ['SFO', 6.020797289396148, 'DEN', 12.041594578792296, 'OAK', 6.029925372672534]], ['SFO', ['SEA', 6.020797289396148, 'DEN', 9.7082439194738]]]
在此显示Array of Array的意思是[ '1',['a',['a1','a2','a3']] ]
主Arrya第0个索引['1']
是正常值,另一个索引是数组['a',['a1','a2','a3']]
但是在第二种情况下,它是JSON数据
{'SEA': {'SFO': 6.020797289396148, 'DEN': 12.041594578792296, 'OAK': 6.029925372672534}, 'SFO': {'SEA': 6.020797289396148, 'DEN': 9.7082439194738}}
示例:
{ "SEA" :{'SFO':6.020797289396148}}
SEA-> {}-SFO-> 6.020797289396148 基本上第二种方法包含一个对象 作为该对象中的对象的对象值包含值6.020797289396148
SEA.SFO使用此即可获得此6.020797289396148的值