Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use two items as key to create dictionary python [duplicate]

Tags:

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) {}) 
like image 684
manxing Avatar asked Apr 12 '12 13:04

manxing


People also ask

Can keys be duplicate in dictionary python?

Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.

Can one key have two values in dictionary python?

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.

Can a dictionary key be duplicated?

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


2 Answers

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.

like image 146
Acorn Avatar answered Oct 05 '22 22:10

Acorn


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]... ] 
like image 36
n00dle Avatar answered Oct 05 '22 22:10

n00dle