I have the following list:
['a:1', 'b:2', 'c:3', 'd:4']
I would like to convert to a ordered dict (using collections
):
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
I have seen solutions using regex here but I am not familiar with regex enough to roll a solution. Any thoughts on this?
d = collections.OrderedDict(el.split(':') for el in your_list)
或者,将值转换为整数:
OrderedDict( (k, int(v)) for k, v in (el.split(':') for el in your_list))
To get the values as integers try something like:
In [67]: lis=['a:1', 'b:2', 'c:3', 'd:4']
In [68]: def func(x):
spl=x.split(':')
return spl[0],int(spl[1])
....:
In [71]: dict(map(func,lis))
Out[71]: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
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.