27

Possible Duplicate:
How do I make a dictionary with multiple keys to one value?

I have 5 columns of data,

 usermac, useragent, area ,videoid, number of requests

I want to use both (usermac,useragent) as key to create a dictionary, since unique combination of (usermac, useragent) represents a unique user.

so the dictionary would be like:

 usermac1, useragent1: area1, videoid1, 10
                       area1, videoid2, 29
 usermac1, useragent2: area1, videoid1, 90
                       area1, videoid2, 34

                        ...

I only know how to create a dictionary with only one item as key. so can anyone help?

my code is:

    for line in fd_in.readlines():
        (mac, useragent, area, videoid, reqs) = line.split()

    video_dict = d1.setdefault((mac,useragent) {})
    video_dict.setdefault(videoid, []).append(float(reqs))

and it has syntax error:

    video_dict = d1.setdefault((mac,useragent) {})
Community
  • 1
  • 1
manxing
  • 3,165
  • 12
  • 45
  • 56
  • @jamylak maybe I should have added my code, I have some syntax error in the code, so I'd appreciate your help, thanks – manxing Apr 12 '12 at 13:50

2 Answers2

46

You can use any (hashable) object as a key for a python dictionary, so just use a tuple containing those two values as the key.

Acorn
  • 49,061
  • 27
  • 133
  • 172
30

I believe you can use a tuple as the key for the dictionary. So you'd have

mydict = {}
mydict[(usermac1,useragent1)] = [ [area1, videoid1, 10],[area1,videoid2,29]... ]
n00dle
  • 5,949
  • 2
  • 35
  • 48