Skip to content Skip to sidebar Skip to footer

Passing String, Integer And Tuple Information As Key For Python Dictionary

I'm trying to create a python dictionary and I would like to use a key that contains strings, numerics & a list/tuple entry. The key should ideally look like ('stringA', 'strin

Solution 1:

The issue here is with your namedtuple definition, not the dictionary key structure itself, which will work just fine, e.g.:

>>> d = {}
>>> d[('1', '2', 3, (4, 5))] = 'foo'>>> d
{('1', '2', 3, (4, 5)): 'foo'}

When the namedtuple reads the field_names parameter, it thinks you're trying to create a field named (integer2, and doesn't realise that you mean it to be a nested tuple.

To define that structure in a namedtuple, you will instead have to have an attribute that is itself a tuple:

>>> from collections import namedtuple
>>> dictKey = namedtuple("dictKey", "stringA stringB stringC integer1 tuple1")
>>> key = dictKey("foo", "bar", "baz", 1, (2, 3, 4))
>>> d[key] = 'bar'>>> d
{dictKey(stringA='foo', stringB='bar', stringC='baz', integer1=1, tuple1=(2, 3, 4)): 'bar',
 ('1', '2', 3, (4, 5)): 'foo'}

You can retrieve the value stored against the key exactly as you can for any other, either with the original namedtuple:

>>> d[key]
'bar'

or a new one:

>>> d[dictKey("foo", "bar", "baz", 1, (2, 3, 4))]
'bar'

Post a Comment for "Passing String, Integer And Tuple Information As Key For Python Dictionary"