0

I have a dictionary that will have many keys. Some keys will have a nested dictionary in it.

I would like to initialize the dictionary before giving it any content just to "announce" beforehand its structure to anyone reading the code. So the dictionary will be something like {"key1": None, "key2": None, ...}. This question teaches how to do this.

I have never seen this pattern, so I'm not quite comfortable in using it. Does anyone spot any problem? What about initializing the nested dictionaries as well?

  • What is it that you are using the dict for? Will the values of each of the root-level key differ from each other? e.g. one is a str, one is another dict, list, or whatever? – tbjorch Mar 04 '21 at 12:54
  • @tbjorch the type of values will diverge across the keys, and as I mentioned there will be nested dictionaries. – guest22654018 Mar 04 '21 at 12:58
  • Ok but based on what you state above, you are able to predict what keys will be populated later on? Would that also mean that you are able to predict the type of each key? – tbjorch Mar 04 '21 at 13:00
  • Right. It will be a "fixed" dictionary. I know exactly what the keys will be beforehand, and the types of the values. – guest22654018 Mar 04 '21 at 13:01
  • I agree with @tbjorch basically he is asking what is it you know for sure and why are you wanting to prepopulate the keys of this dictionary and not others? – Daniel Butler Mar 04 '21 at 13:02

2 Answers2

0

I haven't seen this before but I'd probably rather make a comment about the dictionary. Style guidelines tell nothing that I could find.

0

A challenge with dictionaries is that it's difficult to know their structure and content if it gets mutated along the way. I would rather suggest looking into what you want to achieve with the dictionary.

Based on your description and the info from the comments: If you know what keys (attributes) to expect, and what type each of the attributes will have, I would recommend creating a class or even better a dataclass. This would provide a better readability for a developer looking at your code and trying to understand what data structure they are working wiith, since they know how an instance of that object would look and what attributes it will contain and also the types of the attributes.

(If you are looking to include type validation etc. you could even look into Pydantic )

Example with dataclass:

from dataclasses import dataclass

@dataclass
class MyDataClass:
    title: str
    body: str
    _id: int


my_instance = MyDataClass("Hello", "World", 2)
my_instance2 = MyDataClass("HEEEY", "UNIVERSE", 3)
print(my_instance)
print(my_instance2)

would output:

MyDataClass(title='Hello', body='World', _id=2)
MyDataClass(title='HEEEY', body='UNIVERSE', _id=3)
tbjorch
  • 1,544
  • 1
  • 8
  • 21