Search code examples
pythondictionarydefaultdict

Python: How to split a string into multiple value spaces in a dictionary


I am starting out with a file in this format:

a ; b
b ; c
c ; d,e

and I need to end up with a dictionary where the keys are from the left-hand side of the arrows and the values are from the right-hand side; AND if there are multiple letters on the right-hand side, they go into MULTIPLE values in the dictionary.

This is my current code:

cleanup = [part for part in [entry.replace('\n','') for entry in myFile]]
lefts = [part[0] for part in [entry.split(' ; ') for entry in cleanup]]
rights = [part[1] for part in [entry.split(' ; ') for entry in cleanup]]



myDict = defaultdict(list) 

for left, right in zip(lefts, rights):
    myDict[left].append(right)

and my current result:

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

which is clearly not what I want -- I need d and e to be in SEPARATE value spaces, but associated with one key, c.

Thank you in advance.


Solution

  • You are very close. What you should do is when you take your right side, split that on comma. So now you should have a list with those individual items:

    ['d', 'e']
    

    Then, instead of using append, use extend:

    for left, right in zip(lefts, rights):
        myDict[left].extend(right.split(','))