1

i have a problem with my code, tried looking up how to fix it and tried multiple methods but its just not going

Here is what i got:

with open("people-data.txt") as f:

children= {}
for line in f.readlines():
    parent, child = line.split("->")
    children[parent] = child

I tried using: children[parent].append(child) and other things.

My file looks like this:

Mary->Patricia
Mary->Lisa
Patricia->Barbara

What I would like is when I use children[Mary] I get ['Patricia', 'Lisa'] but what my code does is give my just 'Lisa' and overrides 'Patricia'.

timgeb
  • 76,762
  • 20
  • 123
  • 145
D. K.
  • 137
  • 10
  • It should be `children[parent] = child`. In your case you would store the key `"parent"` and overwrite it. – Anton vBR Nov 25 '18 at 16:22
  • ye sorry, my mistake from copying, let my correct it – D. K. Nov 25 '18 at 16:23
  • You need to use a defaultdict from collections. – Anton vBR Nov 25 '18 at 16:24
  • Of course it overwrites. What else would `children[parent] = child` do? You need to keep lists in each value of the dict, which can be easily done by using `children = defaultdict(list)` and `children[parent].append(child)` – DeepSpace Nov 25 '18 at 16:24

1 Answers1

2

I tried using: children[parent].append(child)

That will work as long as you are using lists for your dictionary-values.

The easiest fix to achieve that would be to make children a defaultdict, i.e.

from collections import defaultdict
children = defaultdict(list)

and then use

children[parent].append(child)

in your code.

Demo:

>>> from collections import defaultdict
>>> children = defaultdict(list)
>>> 
>>> children['Peter'].append('Bob')
>>> children['Peter'].append('Alice')
>>> children['Mary'].append('Joe')
>>> 
>>> children
defaultdict(list, {'Mary': ['Joe'], 'Peter': ['Bob', 'Alice']})
timgeb
  • 76,762
  • 20
  • 123
  • 145