I'm trying to create a dict from a list with Python 2.7
This is my list :
x = ['+proj=geos',
'lon_0=86.5',
'h=35785993.3373',
'x_0=0',
'y_0=0',
'a=6378160',
'b=6356775',
'units=m',
'no_defs ']
In every element from my list, there are my keys and my values separated with the char "=". As a result, i want this :
d = {"+proj": "geos", "lon_0": "86.5", "h": "35785993.3373", "x_0": "0", "y_0": "0", "a": "6378160", "b": "6356775", "units": "m"}
You can use dict
with a generator expression with split
and a filter:
>>> dict(y.split("=") for y in x if "=" in y)
{'+proj': 'geos',
'a': '6378160',
'units': 'm',
'b': '6356775',
'y_0': '0',
'x_0': '0',
'h': '35785993.3373',
'lon_0': '86.5'}
Try something like this:
d = {}
for i in x:
if '=' not in i: continue # skip if no pair given
key, value = i.split('=') # split into pair
d.update({key : value}) # update dict with pair
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.