问题
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", "stringB", "stringC", integer1, (integer2, integer3, integer4))
I tried to create a namedtuple based on this documentation as follows
from collections import namedtuple
dictKey = namedtuple('dictKey', 'stringA stringB stringC integer1
(integer2 integer3 integer4)')
but it throws me a ValueError saying it can only contain alphanumeric characters and underscores. So
How can I create a dictionary key which contains a tuple?
How to effectively use the dictionary key (especially the tuple it contains) to retrieve information from the dictionary?
回答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'
来源:https://stackoverflow.com/questions/28415736/passing-string-integer-and-tuple-information-as-key-for-python-dictionary