Python 2.7:从特殊格式的列表对象中创建字典对象

时间:2014-05-28 14:43:52

标签: python list python-2.7 dictionary

我有一个列表类型对象,如:

     f = [77.0, 'USD', 77.95, 
     103.9549, 'EUR', 107.3634,
     128.1884, 'GBP', 132.3915,
     0.7477, 'JPY', 0.777]

我想创建一个如下字典:

d = 
{'EUR': [103.9549, 107.3634],
'GBP': [128.1884, 132.3915],
'JPY': [0.7477, 0.777],
'USD': [77.0, 77.95]}

我尝试使用这些答案Convert a list to a dictionary in PythonMake dictionary from list with python

但是,无法找到正确的方法。

截至目前,我的解决方案是:

cs = [str(x) for x in f if type(x) in [str, unicode]]
vs = [float(x) for x in f if type(x) in [int, float]]
d =  dict(zip(cs, [[vs[i],vs[i+1]] for i in range(0,len(vs),2)]))

但是,什么是智能单行?

4 个答案:

答案 0 :(得分:7)

怎么样:

In [5]: {f[i+1]: [f[i], f[i+2]] for i in range(0, len(f), 3)}
Out[5]: 
{'EUR': [103.9549, 107.3634],
 'GBP': [128.1884, 132.3915],
 'JPY': [0.7477, 0.777],
 'USD': [77.0, 77.95]}

答案 1 :(得分:2)

使用zip,dict comprehension:

>>> f = [
...     77.0, 'USD', 77.95,
...     103.9549, 'EUR', 107.3634,
...     128.1884, 'GBP', 132.3915,
...     0.7477, 'JPY', 0.777
... ]
>>> {currency: [v1, v2] for v1, currency, v2 in zip(*[iter(f)]*3)}
{'JPY': [0.7477, 0.777],
 'USD': [77.0, 77.95],
 'GBP': [128.1884, 132.3915],
 'EUR': [103.9549, 107.3634]}

[iter(f)]*3来自itertools recipes中的grouper

答案 2 :(得分:1)

这必须是单行历史上最丑陋的单行,但嘿,它有效:

print dict(zip((i[1] for i in zip(f[::3],f[1::3],f[2::3])), ([i[0],i[2]] for i in zip(f[::3],f[1::3],f[2::3]))))

答案 3 :(得分:0)

>>> f = [77.0, 'USD', 77.95,
         103.9549,'EUR', 107.3634,
         128.1884, 'GBP', 132.3915,
         0.7477, 'JPY', 0.777]
>>> {f[v+1]:[f[v],f[v+2]] for v in range(0, len(f), 3)}
{'JPY': [0.7477, 0.777], 'USD': [77.0, 77.95], 'GBP': [128.1884, 132.3915], 'EUR': [103.9549, 107.3634]}