manxing
manxing

Reputation: 3305

list indices must be integer python

I have a dictionary, user_dict, and create a list for each user value, this list contains json object:

user_dict[user].append(obj)

Now I want to print all the items in this dictionary, but only select some field from each item in the list, so the dictionary is like this, I only list one user here

{u'user1':[{u'host_dst': {u'addr': u'195.149.144.60', u'vid': 0, u'port': 80},

            'usi': '7932fee11ba72ae84180044d75521368', u'host_src': {u'addr': u'83.233.59.215', 

            u'vid': 0, u'port': 51068},item2...]}

What I did is:

for item in user_dict.values():
    fd_out1.write("%s\t%s\n" % (item["host_dst"][addr],item["host_dst"]["vid"]))

and it returns:

TypeError: list indices must be integers, not str

Previously for example, I used obj["host_dst"][addr] to represent the value 195.149.144.60, and it works fine, but here when I want to print out something, it cannot work. Can anyone help? Many thanks!!

Upvotes: 0

Views: 3424

Answers (3)

xvatar
xvatar

Reputation: 3259

you missed a bracket in your post

after proper formatting, your data looks like this

{
  u'user1': [
                {
                  u'host_dst': {
                                  u'addr': u'195.149.144.60',
                                  u'vid': 0,
                                  u'port': 80
                               },

                  'usi': '7932fee11ba72ae84180044d75521368',
                  u'host_src': {
                                  u'addr': u'83.233.59.215', 
                                  u'vid': 0, 
                                  u'port': 51068
                                }
                 },
                item2,
                ...
           ]
}

so each item in your loop is a list

you should print out something like item[0]["host_dst"][addr]

Upvotes: 2

user278064
user278064

Reputation: 10170

The first item that you retrieve is the following, which is a list and you cannot access to its elements using a string like in a dict.

[{u'host_dst': {u'addr': u'195.149.144.60', u'vid': 0, u'port': 80},
        'usi': '7932fee11ba72ae84180044d75521368', u'host_src': {u'addr': '83.233.59.215', 
        'u'vid': 0, u'port': 51068},item2...]}

You should use an integer.

Upvotes: 0

chepner
chepner

Reputation: 531205

The values of user_dict are lists, not dictionaries. It appears that it may be a list with just a single item, though, so try

for item in user_dict.values():
    fd_out1.write("%s\t%s\n" % (item[0]["host_dst"][addr],item[0]["host_dst"]["vid"]))

Upvotes: 0

Related Questions