Python Forum
Most efficient way to define sub keys of a dictionary? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Most efficient way to define sub keys of a dictionary? (/thread-16277.html)



Most efficient way to define sub keys of a dictionary? - wrybread - Feb-20-2019

Suppose I have a dictionary named "properties".

properties = {}

And there's a few different items that will be subkeys.

properites["item1"] = {}

One of the subkeys is "color".

properites["item1"]["color"] = "blue"

What's the most efficient way to define item2's color if item 2 doesn't exist in the properties dict yet? So:

properties = {}
properties["item2"]["color"] = "black"

# throws a KeyError: 'item2'

Currently I'm solving this with a roundabout declaration:

properites = {}
properties["item2"] = {}
properties["item2"]["color"] = "black"

But I'm guessing there's a better way.


RE: Most efficient way to define sub keys of a dictionary? - snippsat - Feb-21-2019

Use defaultdict.
>>> from collections import defaultdict
>>> 
>>> properites = defaultdict(dict)
>>> properites["item2"]["color"] = "black"
>>> properites
defaultdict(<class 'dict'>, {'item2': {'color': 'black'}})
>>> properites['item2']['color']
'black'