Skip to content

Instantly share code, notes, and snippets.

@germ13
Created October 18, 2023 20:55
Show Gist options
  • Save germ13/4d8cb7574cdbd7dfa8e81d34712fc0a3 to your computer and use it in GitHub Desktop.
Save germ13/4d8cb7574cdbd7dfa8e81d34712fc0a3 to your computer and use it in GitHub Desktop.
Python dictionary traversal given path array
from functools import reduce
import operator
# 4bb
k = ["a", "b", "c", "d"]
ar = {}
ar["a"] = {}
ar["a"]["b"] = {}
ar["a"]["b"]["c"] = {}
ar["a"]["b"]["c"]["d"] = "ThePrice"
k_sub = k[:-1]
reduce(operator.getitem,k_sub, ar)[k[-1]] = reduce(operator.getitem, k, ar) + "gogogo"
#>>> ar
# {'a': {'b': {'c': {'d': 'ThePricegogogo'}}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment