Joe Smart
Joe Smart

Reputation: 763

Multiple Values for a single key in a dictionary

I am currently writing a script that extracts data from an xml and writes it into an html file for easy viewing on a webpage.

Each piece of data has 2 pieces of "sub data": Owner and Type.

In order for the html to work properly I need the "owner" string and the "type" string to be written in the correct place. If it was just a single piece of data then I would use dictionaries and just use the data name as the key and then write the value to html, however there are 2 pieces of data.

My question is, can a dictionary have 2 values (in my case owner and type) assigned to a single key?

Upvotes: 2

Views: 1517

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122116

Any object can be a value in a dictionary, so you can use any collection to hold more than one value against the same key. To expand my comments into some code samples, in order of increasing complexity (and, in my opinion, readability):

Tuple

The simplest option is a two-tuple of strings, which you can access by index:

>>> d1 = {'key': ('owner', 'type')}
>>> d1['key'][0]
'owner'
>>> d1['key'][1]
'type'

Dictionary

Next up is a sub-dictionary, which allows you to access the values by key name:

>>> d2 = {'key': {'owner': 'owner', 'type': 'type'}}
>>> d2['key']['owner']
'owner'
>>> d2['key']['type']
'type'

Named tuple

Finally the collections module provides namedtuple, which requires a little setup but then allows you to access the values by attribute name:

>>> from collections import namedtuple
>>> MyTuple = namedtuple('MyTuple', ('owner', 'type'))
>>> d3 = {'key': MyTuple('owner', 'type')}
>>> d3['key'].owner
'owner'
>>> d3['key'].type
'type'

Using named keys/attributes makes your subsequent access to the values clearer (d3['key'].owner and d2['key']['owner'] are less ambiguous than d1['key'][0]).

Upvotes: 2

Abhijit
Abhijit

Reputation: 63767

As long as keys are hash-able you can have keys of any format. Note, tuples are hash-able so that would be a possible solution to your problem

Make a tuple of case-owner and type and use it as a key to your dictionary.

Note, generally all objects that are hashable should also be immutable, but not vice-versa. So

Upvotes: 0

Related Questions