传递String,整数和元组信息作为python字典的关键 [英] Passing String, integer and tuple information as key for python dictionary
问题描述
我正在尝试创建一个python字典,我想使用一个包含字符串,数字和列表/元组条目。关键应该理想地看起来像
(stringA,stringB,stringC,integer1,(integer2,integer3,整数4))
我试图根据这个文档如下
from collections import namedtuple
pre>
dictKey = namedtuple('dictKey','stringA stringB stringC integer1
(integer2 integer3 integer4)'
但是它给我一个ValueError,它只能包含字母数字字符和下划线。所以
如何创建一个包含元组的字典键?
如何有效地使用字典键(特别是元组it
包含)从字典中检索信息?
解决方案这里的问题是您的
namedtuple
定义,而不是字典键结构本身,这将工作正常,例如:>>> d = {}
>>> d [('1','2',3,(4,5))] ='foo'
>>> d
{('1','2',3,(4,5)):'foo'}
当$ code> namedtuple 读取
field_names
参数时,它认为您正在尝试创建一个字段名为(integer2
,并没有意识到你的意思是它是一个嵌套的元组
。
要在
namedtuple
中定义该结构,您将需要具有一个本身为元组
:>>从集合导入namedtuple
>> ;> dictKey = namedtuple(dictKey,stringA stringB stringC integer1 tuple1)
>> key = dictKey(foo,bar,baz 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'}
您可以检索存储在ke上的值或者与原始的
namedtuple
相同:>>> d [key]
'bar'
或一个新的:
>>> d [dictKey(foo,bar,baz,1,(2,3,4))]
'bar'
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?
解决方案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 thefield_names
parameter, it thinks you're trying to create a field named(integer2
, and doesn't realise that you mean it to be a nestedtuple
.To define that structure in a
namedtuple
, you will instead have to have an attribute that is itself atuple
:>>> 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'
这篇关于传递String,整数和元组信息作为python字典的关键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!