0
votes

I have a file in which there are 2 names on each line. Let's say i have the following input:

name1 name2
name3 name4
name1 name5

I want to make a dictionary like this:

name1 : [name2, name5]
name2 : name1
name3 : name4
name4 : name3
name5 : name1

Here is the code I made but i can't figure out what i did wrong..

d = {} 
for i in range(len(l)): # consider l the input
    d[l[i]] = ""

for i in range(0, len(l), 2):
    e1 = l[i]
    e2 = l[i+1]

    d.update({e1 : [d[e1], e2]}) #i think the update operation is wrong here..
    d.update({e2 : [d[e2], e1]})
3
Can you add the output (e.g.: print(d)) of your program to make it easier to understand whats going wrong? - Stefan Scheller
... also print(l) at the beginning. - Austin

3 Answers

1
votes

You can change the two critical lines to:

d.setdefault(e1, []).append(e2)
d.setdefault(e2, []).append(e1)

This will start an empty list if the key is not present and then fill it.

0
votes

You can use defaultdict:

>>> from collections import defaultdict

>>> d = defaultdict(list)
>>> for i in range(0, len(l), 2):
...     d[e1].append(e2)
0
votes

Create a defaultdict d which sets empty lists as the initial values for every key and populate them as you iterate over l.

from collections import defaultdict
l = ['name1', 'name2', 'name3', 'name4', 'name1', 'name5'] # Values come in pairs
d = defaultdict(list) # Defaults all keys to []

for i in range(0, len(l), 2):
    d[l[i]].append(l[i+1])
    d[l[i+1]].append(l[i])