-2

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
bitsmack
  • 1,324
  • 3
  • 21
  • 31

1 Answers1

1

Perhaps something like this (assuming dictname is defined)?

dictname['dict1'] = dict1

If not:

dictname = {'dict1': dict1}

and then...

dictname['dict1'].keys()
>>> dict_keys(['key1', 'key2', 'key3'])
flevinkelming
  • 690
  • 7
  • 8