如果名称在字符串变量中,如何通过名称访问对象?

时间:2021-07-27 02:58:17

I have numerous dictionaries. I have their names stored in a list (as strings). How can I programmatically access a specific dictionary using a name stored as a string?

我有很多词典。我将他们的名字存储在一个列表中(作为字符串)。如何使用存储为字符串的名称以编程方式访问特定字典?

>>> dict1 = dict([('key1',1), ('key',2), ('key3',3)])
>>> dict1.keys()
dict_keys(['key2', 'key1', 'key3'])
>>> dictname = 'dict1'
>>> dictname.keys()
AttributeError: 'str' object has no attribute 'keys'

I understand why this doesn't work, but can it be done some other way?

我理解为什么这不起作用,但可以通过其他方式完成吗?

1 个解决方案

#1


1  

Perhaps something like this (assuming dictname is defined)?

也许这样的事情(假设dictname被定义)?

dictname['dict1'] = dict1

If not:

dictname = {'dict1': dict1}

and then...

dictname['dict1'].keys()
>>> dict_keys(['key1', 'key2', 'key3'])

#1


1  

Perhaps something like this (assuming dictname is defined)?

也许这样的事情(假设dictname被定义)?

dictname['dict1'] = dict1

If not:

dictname = {'dict1': dict1}

and then...

dictname['dict1'].keys()
>>> dict_keys(['key1', 'key2', 'key3'])