将列表元素转换为字典python

时间:2013-06-10 21:55:52

标签: python list dictionary

我有一个下面格式的列表

['iad-cgnt:248.600000,ord-cgnt:319.301775,iad-mci:331.185117,nyc-inap:316.122925,hkg-pccw:452.789753,ord-tata:243.000000,sjc-l3:321.487964,pvg-cu2:40.912496,nyc-bgp:382.419130,nyc-cgnt:332.477115,bgl-rel:311.344224,pvg-cu1:38.750000']

我需要以这种格式从这个列表构建一个字典:

{'iad-cgnt' : 248.600000 , 'ord-cgnt':319.301775 } ... and  so on. 

你能建议怎么做吗?

3 个答案:

答案 0 :(得分:1)

假设:

data = 'iad-cgnt:248.600000,ord-cgnt:319.301775,iad-mci:331.185117,nyc-inap:316.122925,hkg-pccw:452.789753,ord-tata:243.000000,sjc-l3:321.487964,pvg-cu2:40.912496,nyc-bgp:382.419130,nyc-cgnt:332.477115,bgl-rel:311.344224,pvg-cu1:38.750000'

您可以使用以下方式获取字典:

dict([item.split(':') for item in data[0].split(',')])

作为输出

{'bgl-rel': '311.344224',
 'hkg-pccw': '452.789753',
 'iad-cgnt': '248.600000',
 'iad-mci': '331.185117',
 'nyc-bgp': '382.419130',
 'nyc-cgnt': '332.477115',
 'nyc-inap': '316.122925',
 'ord-cgnt': '319.301775',
 'ord-tata': '243.000000',
 'pvg-cu1': '38.750000',
 'pvg-cu2': '40.912496',
 'sjc-l3': '321.487964'}

答案 1 :(得分:0)

字典理解:

L = ['iad-cgnt:248.600000,ord-cgnt:319.301775,iad-mci:331.185117,...pvg-cu1:38.750000']
{k: float(v) for k, v in (item.split(':') for item in L[0].split(','))}

值为浮点数的结果:

{'bgl-rel': 311.344224,
 'hkg-pccw': 452.789753,
 'iad-cgnt': 248.6,
 'iad-mci': 331.185117,
 'nyc-bgp': 382.41913,
 'nyc-cgnt': 332.477115,
 'nyc-inap': 316.122925,
 'ord-cgnt': 319.301775,
 'ord-tata': 243.0,
 'pvg-cu1': 38.75,
 'pvg-cu2': 40.912496,
 'sjc-l3': 321.487964}

答案 2 :(得分:0)

列表中的项目非常接近要开始的字典的字符串表示形式, 一个小小的文字摆弄它:

zot = ['iad-cgnt:248.600000,ord-cgnt:319.301775,iad-mci:331.185117,nyc-inap:316.122925,hkg-pccw:452.789753,ord-tata:243.000000,sjc-l3:321.487964,pvg-cu2:40.912496,nyc-bgp:382.419130,nyc-cgnt:332.477115,bgl-rel:311.344224,pvg-cu1:38.750000']
s = '{"'+zot[0].replace(',', ',"').replace(':', '":')+'}'
d = eval(s)
print d.keys()

给出字典的键:

['iad-cgnt', 'nyc-bgp', 'ord-cgnt', 'bgl-rel', 'nyc-cgnt', 'nyc-inap', 'sjc-l3', 'hkg-pccw', 'pvg-cu1', 'pvg-cu2', 'ord-tata', 'iad-mci']