Shayne Jonas Shayne Jonas - 16 days ago 5
Python Question

How can I iterate over a dict which is indexed by a dict?

If I have an iteration like:

for index in my_dict:
print index.keys()


Is
index
possible to be a dictionary in this case? If possible, could you please give me an example of what
my_dict
will look like?

Answer

index cannot be a dict as dictionary keys must be hashable types. Since dictionaries are themselves not hashable, they can not serve as keys to another dictionary.

for index in my_dict

iterates over the dictionary keys and will yield the same result as

for index in my_dict.keys()

You can however have a dictionary nested as a value of another dictionary:

{'parent': {'nested': 'some value'}}
#          ^   nested dictionary  ^