Converting colon separated list into a dict?

前端 未结 3 630
我在风中等你
我在风中等你 2020-12-18 11:43

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          


        
相关标签:
3条回答
  • 2020-12-18 12:11

    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.

    0 讨论(0)
  • 2020-12-18 12:22

    You can do:

    >>> li=['a:1', 'b:2', 'c:3']
    >>> dict(e.split(':') for e in li)
    {'a': '1', 'c': '3', 'b': '2'}
    
    0 讨论(0)
  • 2020-12-18 12:25

    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.

    return dict(map(lambda s : map(str.strip, s.split(':')), rlist))
    
    0 讨论(0)
提交回复
热议问题