Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7: making a dictionary object from a specially-formatted list object

I have a list type object like:

     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 like below:

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

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

But, couldn't figure out the right way.

As of now, 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 would be a smart one-liner ?

like image 261
kmonsoor Avatar asked Dec 25 '22 08:12

kmonsoor


1 Answers

How 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]}
like image 183
NPE Avatar answered Dec 31 '22 12:12

NPE