0
     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?

0

3 Answers 3

4

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.

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

Comments

2

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

Comments

0

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.

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.