Passing String, integer and tuple information as key for python dictionary

守給你的承諾、 提交于 2019-12-11 11:36:17

问题


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

  1. How can I create a dictionary key which contains a tuple?

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!