0

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]})
2
  • Can you add the output (e.g.: print(d)) of your program to make it easier to understand whats going wrong? Commented Apr 16, 2020 at 8:28
  • ... also print(l) at the beginning. Commented Apr 16, 2020 at 8:29

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use defaultdict:

>>> from collections import defaultdict

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

Comments

0

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])

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.