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) {})
Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.
In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry. To accomplish the need of duplicates keys, i used a List of type KeyValuePair<> .
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.
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]... ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With