Python Forum
Most efficient way to define sub keys of a dictionary?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Most efficient way to define sub keys of a dictionary?
#1
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.
Reply
#2
Use defaultdict.
>>> from collections import defaultdict
>>> 
>>> properites = defaultdict(dict)
>>> properites["item2"]["color"] = "black"
>>> properites
defaultdict(<class 'dict'>, {'item2': {'color': 'black'}})
>>> properites['item2']['color']
'black'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  A more efficient code titanif 2 487 Oct-17-2023, 02:07 PM
Last Post: deanhystad
  Cleaning my code to make it more efficient BSDevo 13 1,357 Sep-27-2023, 10:39 PM
Last Post: BSDevo
  Making a function more efficient CatorCanulis 9 1,825 Oct-06-2022, 07:47 AM
Last Post: DPaul
  I there a more efficient way of printing ? Capitaine_Flam 7 3,482 Dec-01-2020, 10:37 AM
Last Post: buran
  Adding keys and values to a dictionary giladal 3 2,466 Nov-19-2020, 04:58 PM
Last Post: deanhystad
  access dictionary with keys from another and write values to list redminote4dd 6 3,232 Jun-03-2020, 05:20 PM
Last Post: DeaD_EyE
  Drop Keys From Dictionary donnertrud 8 3,681 May-30-2020, 11:39 AM
Last Post: DeaD_EyE
  A more efficient way of comparing two images in a python vukan 0 2,015 Mar-17-2020, 11:39 AM
Last Post: vukan
  how to make iterative search more efficient renergy 2 2,263 Jan-03-2020, 03:43 PM
Last Post: stullis
  Problem adding keys/values to dictionary where keynames = "property" and "value" jasonashaw 1 2,034 Dec-17-2019, 08:00 PM
Last Post: jasonashaw

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020