简体   繁体   English

Python:将'key:value'元素的列表解析为'key'的字典:值对

[英]Python: Parse list of 'key:value' elements to dictionary of 'key': value pairs

I have the following list: 我有以下列表:

['a:1', 'b:2', 'c:3', 'd:4']

I would like to convert to a ordered dict (using collections ): 我想转换为有序的dict(使用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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM