0

I know there's a similar question:

How to append to a dictionary of dictionaries

but the answers aren't working for me. My problem is as follows. If I need to add a new key: value pair to a Python dictionary, then

my_dict[key] = value

is always safe (as long as key is not a mutable type), whether my_dict had been already initialized or not.

However, if I want my_dict to be a dictionary of dictionaries, then

my_dict[keyA][keyB] = value

doesn't work, unless I already initialized my_dict[keyA] as an empty dictionary. So what I'm doing right now is:

class dict_of_dict():
    def __init__(self):
        self.ddict = {}
    
    def update(self, keyA, keyB, value):
        if not(keyA in self.ddict.keys()):
            self.ddict[keyA] = {}
        self.ddict[keyA][keyB] = value

a = dict_of_dict()
a.update(0, 3, "foobar")

a.ddict

This works, but I feel like it's overkill. Is there a more compact/Pythonic but still readable solution?

DeltaIV
  • 4,773
  • 12
  • 39
  • 86

0 Answers0