简体   繁体   English

将冒号分隔的列表转换为字典?

[英]Converting colon separated list into a dict?

I wrote something like this to convert comma separated list to a dict.我写了这样的东西来将逗号分隔的列表转换为字典。

def list_to_dict( rlist ) :
    rdict = {}
    i = len (rlist)
    while i:
        i = i - 1
        try :
            rdict[rlist[i].split(":")[0].strip()] = rlist[i].split(":")[1].strip()
        except :
            print rlist[i] + ' Not a key value pair'
            continue


    return rdict

Isn't there a way to有没有办法

for i, row = enumerate rlist
    rdict = tuple ( row ) 

or something?或者其他的东西?

If I understand your requirements correctly, then you can use the following one-liner.如果我正确理解您的要求,那么您可以使用以下单行。

def list_to_dict(rlist):
    return dict(map(lambda s : s.split(':'), rlist))

Example:例子:

>>> list_to_dict(['alpha:1', 'beta:2', 'gamma:3'])
{'alpha': '1', 'beta': '2', 'gamma': '3'}

You might want to strip() the keys and values after splitting in order to trim white-space.您可能希望在拆分后strip()键和值以修剪空白。

return dict(map(lambda s : map(str.strip, s.split(':')), rlist))

You can do:你可以做:

>>> li=['a:1', 'b:2', 'c:3']
>>> dict(e.split(':') for e in li)
{'a': '1', 'c': '3', 'b': '2'}

You mention both colons and commas so perhaps you have a string with key/values pairs separated by commas, and with the key and value in turn separated by colons, so:你提到了冒号和逗号,所以也许你有一个字符串,键/值对用逗号分隔,键和值依次用冒号分隔,所以:

def list_to_dict(rlist):
    return {k.strip():v.strip() for k,v in (pair.split(':') for pair in rlist.split(','))}

>>> list_to_dict('a:1,b:10,c:20')
{'a': '1', 'c': '20', 'b': '10'}
>>> list_to_dict('a:1, b:10, c:20')
{'a': '1', 'c': '20', 'b': '10'}
>>> list_to_dict('a   :    1       , b:    10, c:20')
{'a': '1', 'c': '20', 'b': '10'}

This uses a dictionary comprehension iterating over a generator expression to create a dictionary containing the key/value pairs extracted from the string.这使用迭代生成器表达式的字典理解来创建包含从字符串中提取的键/值对的字典。 strip() is called on the keys and values so that whitespace will be handled.对键和值调用strip()以便处理空格。

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

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