2

I am trying to read contents from file which has the following content

XXX f,d,c,e
DDD f,d,c,g
ZZZ f,d,h,g
KKK c,c,d,d

I have to read this as a dictionary in the below format. The below should be my final output -

{'XXX': ['f','d','c','e'], 'DDD': ['f','d','c','g'], 'ZZZ': ['f','d','h','g'], 'KKK': ['c','c','d','d']}

But I managed to read it as dictionary in the below format. But the values are not in list format. Current output

{'XXX': 'f,d,c,e', 'DDD': 'f,d,c,g', 'ZZZ': 'f,d,h,g', 'KKK': 'c,c,d,d'}

Can someone help to convert the values as list or directly read it as list from file?

3
  • See str.split(',') Commented Aug 2, 2018 at 7:49
  • Do you have some code to show what you have already tried? Please add your code. Commented Aug 2, 2018 at 7:49
  • 1
    But the value of the desired output dict is not a list of strings. Commented Aug 2, 2018 at 7:52

2 Answers 2

5

Use str.split(",")

Ex:

d = {'XXX': 'f,d,c,e', 'DDD': 'f,d,c,g', 'ZZZ': 'f,d,h,g', 'KKK': 'c,c,d,d'}
d = {k: v.split(",") for k,v in d.items()}
print(d)

Output:

{'XXX': ['f', 'd', 'c', 'e'], 'ZZZ': ['f', 'd', 'h', 'g'], 'KKK': ['c', 'c', 'd', 'd'], 'DDD': ['f', 'd', 'c', 'g']}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Rakesh for your help. I got the output.
2

Try this in one line:

a = '''XXX f,d,c,e
    DDD f,d,c,g
    ZZZ f,d,h,g
    KKK c,c,d,d'''

{k:v.split(',') for k,v in {l.split()[0]:l.split()[1] for l in a.split('\n')}.items()}

the out put:

{'XXX': ['f', 'd', 'c', 'e'],
 'DDD': ['f', 'd', 'c', 'g'],
 'ZZZ': ['f', 'd', 'h', 'g'],
 'KKK': ['c', 'c', 'd', 'd']}

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.