Search code examples
pythonpython-3.xdefaultdict

Initializing python Defaultdict


Is there a way to initialize a dict the following way:

component_map = {}
component_map[component] = {'in': [], 'out': [], 'degree': 0}

For example, I can create a defaultdict that will give me a [] by default, like this:

from collections import defaultdict
component_map = defaultdict(list)
component_map['component']
# []

How would I initialize it so that calling component_map['component'] returns {'in': [], 'out': [], 'degree': 0} ?


Solution

  • Like this:

    component_map = defaultdict(lambda: {'in': [], 'out': [], 'degree': 0})