6

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?

Huy Vo
  • 2,418
  • 6
  • 22
  • 43
Victor
  • 427
  • 1
  • 6
  • 19
  • 4
    Can you give example of the input and expected output? A colon separated list doesn't make a lot of sense, lists are separated by being a collection of distinct elements, they do not need a delimiter. – Paul Rooney Feb 06 '17 at 01:46
  • `{item.split(":") for item in rlist if ":" in item}`. If that doesn't work maybe put `tuple(item.split(":"))`. If not this is a lazy slow way`{item.split(":")[0]: item.split(":")[1] for item in rlist}` Also since this is converting a string to a dictionary look into `ast.literaleval` and json. – justengel Feb 06 '17 at 01:49
  • …or perhaps you are attempting to read a CSV-formatted file, in which case using the [csv module](https://docs.python.org/3/library/csv.html) is probably a better way. – spectras Feb 06 '17 at 01:50
  • 2
    what is ur input ? – James Sapam Feb 06 '17 at 02:09
  • Does this answer your question? [Convert list of strings to dictionary](https://stackoverflow.com/questions/22980977/convert-list-of-strings-to-dictionary) – Georgy Dec 11 '20 at 12:47

3 Answers3

6

You can do:

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

If the list of strings require stripping, you can do:

>>> li=["a:1\n", "b:2\n", "c:3\n"]
>>> dict(t.split(":") for t in map(str.strip, li))
{'a': '1', 'b': '2', 'c': '3'}

Or, also:

>>> dict(t.split(":") for t in (s.strip() for s in li))
{'a': '1', 'b': '2', 'c': '3'}
dawg
  • 98,345
  • 23
  • 131
  • 206
5

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))
5gon12eder
  • 24,280
  • 5
  • 45
  • 92
1

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.

mhawke
  • 84,695
  • 9
  • 117
  • 138