manxing
manxing

Reputation: 3305

how to use string as list's indices in Python

     for line in f.readlines():
     (addr, vlanid, videoid, reqs, area) = line.split()

     if vlanid not in dict:
          dict[vlanid] = []

     video_dict = dict[vlanid]

     if videoid not in video_dict:
         video_dict[videoid] = []

     video_dict[videoid].append((addr, vlanid, videoid, reqs, area))

Here is my code, I want to use videoid as indices to creat a list. the real data of videoid are different strings like this : FYFSYJDHSJ

I got this error message:

video_dict[videoid] = []
TypeError: list indices must be integers, not str

But now how to add identifier like 1,2,3,4 for different strings in this case?

Upvotes: 0

Views: 1605

Answers (3)

Makoto
Makoto

Reputation: 106430

As suggested above, creating dictionaries would be the most ideal code to implement. (Although you should avoid calling them dict, as that means something important to Python.

Your code may look something like what @aix had already posted above:

for line in f.readlines():
    d = dict(zip(("addr", "vlanid", "videoid", "reqs", "area"), tuple(line.split())))

You would be able to do something with the dictionary d later in your code. Just remember - iterating through this dictionary will mean that, if you don't use d until after the loop is complete, you'll only get the last values from the file.

Upvotes: 0

eumiro
eumiro

Reputation: 212875

Don't use dict as a variable name. Try this (d instead of dict):

d = {}
for line in f.readlines():
    (addr, vlanid, videoid, reqs, area) = line.split()
    video_dict = d.setdefault(vlanid, {})
    video_dict.setdefault(videoid, []).append((addr, vlanid, videoid, reqs, area))

Upvotes: 2

NPE
NPE

Reputation: 500337

Use a dictionary instead of a list:

if vlanid not in dict:
    dict[vlanid] = {}

P.S. I recommend that you call dict something else so that it doesn't shadow the built-in dict.

Upvotes: 4

Related Questions