-4

我有一个格式如下的列表

['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. 

你能建议怎么做吗?

4

3 回答 3

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'}
于 2013-06-10T21:59:54.903 回答
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']
于 2013-06-10T22:57:40.510 回答
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}
于 2013-06-10T22:10:53.930 回答