BadAtLaTeX
BadAtLaTeX

Reputation: 704

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.

Upvotes: 0

Views: 298

Answers (2)

Saksham Varma
Saksham Varma

Reputation: 2130

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

Upvotes: 1

Nir Alfasi
Nir Alfasi

Reputation: 53535

You shouldn't use the following solution, which modifies globals() (these kind of environment manipulation are error-prone and should be avoided as much as possible!):

dict_one = { 'a': 123, 'b': 234 }
dict_two = { 'a': 567, 'b': 678 }

output = {}
for x in dict_one.keys():
    submap = output.get(x, {})
    submap["dict_one"] = dict_one[x]
    output[x] = submap

for x in dict_two.keys():
    submap = output.get(x, {})
    submap["dict_two"] = dict_two[x]
    output[x] = submap


# part 2
globs = globals()

for x in output:
    globs[x] = output[x]

print a['dict_two'] # 567

What you should do, is simply use output as an abstraction layer (ignore "part 2" of the previous code snippet and instead use):

print output['a']['dict_one'] #123

Upvotes: 1

Related Questions