0

I have data like following:

data = """
a:b,c,a
b:c,d
c:b
d:c
"""

I want to convert this string into a dictionary like this:

data_dict = {'a':['b','c','a'],'b':['c','d'],'c':['b'], 'd':['c']}

I tried:

data_list = data.strip('\n').split('\n')
data_str = ", ".join( repr(i) for i in data_list )
data_dict = {}

for i in range(len(data_list)):
    keys, values = data_list[i].split(':')
    key = keys.split('\t')
    value = values.split('\t')
    data_dict = dict(zip(key, value))
    print data_dict

But unfortunately, i got:

{'a':'b,c,a'}
{'b':'c,d'}
{'c':'b'} 
{'d':'c'}

Could anyone helps me out? Many thanks.

1 Answer 1

1

How about something like:

>>> kvs = (line.split(":", 1) for line in data.strip().splitlines())
>>> d = {k: v.split(",") for k,v in kvs}
>>> d
{'a': ['b', 'c', 'a'], 'c': ['b'], 'b': ['c', 'd'], 'd': ['c']}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.