Python 2.7: creating a dictionary object from a specially formatted list object

I have a list type object, for example:

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

I want to create a dictionary as shown below:

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

I tried using these answers Convert a list to a dictionary in Python and Make a dictionary from a list using python .

But, I could not understand the right way.

At the moment, my solution is:

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)]))

but what will be smart single line?

+4
source share
4 answers

What about:

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]}
+7
source

Using zip, understanding dict:

>>> 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)]*3came out of grouperthe itertoolsrecipes .

+2
source

, , :

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]))))
+1
>>> 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]}
0

Source: https://habr.com/ru/post/1542350/


All Articles