Keenan
Keenan

Reputation: 2037

python: creating a list inside a dictionary

I just started using python and I'm trying to create a program that will read a file that looks like this:

AAA x 111
AAB x 111
AAA x 112
AAC x 123
...

the file is 50 lines long and I'm trying to make the letters into keys in a dictionary and the numbers lists that correspond with the keys.

I want the output to look like this:

{AAA: ['111', '112'], AAB: ['111'], AAC: [123], ...}

This is what I've tried

file = open("filename.txt", "r") 
readline = file.readline().rstrip()
while readline!= "":
    list = []
    list = readline.split(" ")
    j = list.index("x")
    k = list[0:j]
    v = list[j + 1:]
    d = {}
    if k not in d == False:
        d[k] = []
    d[k].append(v)
    readline = file.readline().rstrip()

I keep getting syntax errors on my if statement and I can't figure out what I've done wrong.

Upvotes: 1

Views: 14063

Answers (4)

acjay
acjay

Reputation: 36521

Sounds like a job for defaultdict! Aside from your missing colon, as mentioned by others, you could replace the whole if with this:

from collections import defaultdict # placed with your other imports, probably
....
d = defaultdict(lambda:[])
d[k].append(v)

Upvotes: 1

Aesthete
Aesthete

Reputation: 18848

Makes your life a little easier with defaultdict

>>> out = defaultdict(list)
>>> with open('test.txt') as f:
      for line in f.readlines():
        x = line.split()
        out[x[0]].append(int(x[2]))

It's also good practice to use the with statement to open files, when possible. Your original example had two entries as str, and one as int, I have just converted all to int here.

Upvotes: 2

Jesse the Game
Jesse the Game

Reputation: 2630

You're missing colons at the ends, also you could write this like:

if k not in d:
    d[k] = [v]
else:
    d[k].append(v)

Upvotes: 3

illya
illya

Reputation: 775

You need colons at the ends of your if statements; this version should work:

   if k in d == False:
      d[k] = []
      d[k].append(v)
   else:
      d[k].append(v)

Upvotes: 2

Related Questions