Skip to content

Instantly share code, notes, and snippets.

@chaddotson
Created September 3, 2020 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chaddotson/12c1dff3814f7c95e0baf629ab2f3c88 to your computer and use it in GitHub Desktop.
Save chaddotson/12c1dff3814f7c95e0baf629ab2f3c88 to your computer and use it in GitHub Desktop.
Using reduce to navigate dictionaries and lists
# Demonstrate reduce to navigate a nested dictionary or list.
from functools import reduce
from operator import getitem
data_dict = {
'a': 12,
'b': [
{
'c': {
'd': [
{
'e': 11,
'f': 72,
'g': 'etc'
},
{
'h': 42,
'i': 24
}
]
}
},
{
'extra': 32
}
]
}
print(reduce(getitem, ['b', 0, 'c', 'd', 1, 'h'], data_dict))
# prints 42
data_list = [
[
[1, 2, 3, 4],
[5, 6, 7, 8]
], [
[9, 10, 11, 12],
[13, 14, 15, 16]
]
]
print(reduce(getitem, [1, 0, 2], data_list))
# prints 11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment