Search code examples
pythondictionarymappingbidirectional

Dictionary keys as dictionary


Question

How can I use keys of a dictionary as the dictionary name and the prior name as the key?

Here's a similar question:
So far I only found this Python bidirectional mapping, which covers the basic function of bidirectional mapping.

I don't want to find the key for values though, but something like this:

dict_one = { 'a': 123, 'b': 234 }
dict_two = { 'a': 567, 'b': 678 }
dict_one['a']
>> 123
dict_two['a']
>> 567
#... some magic (not simply defining a dict called 'a' though)
a['dict_one']
>> 123
a['dict_two']
>> 567

Situation

I have a number of dictionaries storing constants for different objects. Every object has the same properties (or are existent for most objects). In order to ease the calling of constants in loops both described ways would be useful.


Solution

  • You can define your own class inherited from dict to achieve this, and override the __getitem__ method. But this solution too adds variables through the globals dictionary, not a recommended practice as mentioned by others before me.

    class mdict(dict):
        def __getitem__(self, item):
            self.normal = dict(self)
            return self.normal[str(globals()[item])]
    
    dict_one = {'a': 123, 'b': 234}
    dict_two = {'a': 567, 'b': 678}
    
    lst = [dict_one, dict_two]
    
    for item in lst:
        for k, v in item.iteritems():
            dd = globals().setdefault(k, mdict())
            dd[str(item)] = v
    
    
    >>> print a['dict_one']
    123
    >>> print b['dict_one']
    234
    >>> print a['dict_two']
    567
    >>> print b['dict_two']
    678