Indexing a Nested List

tags: #python/documentation/dictionaries

You can access inner keys of nested dictionary by using the following syntax:

dictionary[<outer_key>][<inner_key>]

Example:

d = {
	 1:{1:50,2:60,5:90},
	 2:{7:55,10:102},
	 4:{10:100,12:40}
	 }
>>> d[1][1]
50

>>> d[2][10]
102

A for loop can be used to iterate over all the keys:

for outer_key in d.keys():
	for inner_key in d[outer_key].keys():
		print(d.[outer_key][inner_key])

Example:

# Example nested dictionary
d = {
	'a': {'x': 1, 'y': 2}, 
	'b': {'x': 3, 'y': 4}, 
	'c': {'x': 5, 'y': 6}
}

# Iterate through outer keys
for outer_key in d.keys():
    # Iterate through inner keys
    for inner_key in d[outer_key].keys():
        # Print the values
        print(f"d[{outer_key}][{inner_key}] =", d[outer_key][inner_key])
d[a][x] = 1
d[a][y] = 2
d[b][x] = 3
d[b][y] = 4
d[c][x] = 5
d[c][y] = 6
Powered by Forestry.md