Using Dictionaries as Keys in Other Dictionaries: 5 Practical Examples

Using Dictionaries as Keys in Other Dictionaries: 5 Practical Examples

Yes, dictionaries can be used as keys in other dictionaries in Python. Here are five examples illustrating this:

  1. Using a Dictionary as a Key with Simple Values:
# Dictionary with another dictionary as a key
nested_dict = {'inner_dict': {'a': 1, 'b': 2}}

# Main dictionary with nested dictionary as a key
main_dict = {nested_dict: 'value'}

print(main_dict)  # Output: { {'inner_dict': {'a': 1, 'b': 2}}: 'value' }
  1. Using a Dictionary as a Key with Tuple Values:
# Dictionary with another dictionary as a key
nested_dict = {'inner_dict': {'a': 1, 'b': 2}}

# Main dictionary with nested dictionary as a key and tuple as value
main_dict = {nested_dict: ('value1', 'value2')}

print(main_dict)  # Output: { {'inner_dict': {'a': 1, 'b': 2}}: ('value1', 'value2') }
  1. Using a Dictionary as a Key with List Values:
# Dictionary with another dictionary as a key
nested_dict = {'inner_dict': {'a': 1, 'b': 2}}

# Main dictionary with nested dictionary as a key and list as value
main_dict = {nested_dict: ['value1', 'value2']}

print(main_dict)  # Output: { {'inner_dict': {'a': 1, 'b': 2}}: ['value1', 'value2'] }
  1. Using Nested Dictionaries as Keys:
# Nested dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

# Main dictionary with nested dictionaries as keys
main_dict = {dict1: 'value1', dict2: 'value2'}

print(main_dict)  # Output: { {'a': 1, 'b': 2}: 'value1', {'c': 3, 'd': 4}: 'value2' }
  1. Using Dictionary of Tuples as Keys:
# Dictionary of tuples
dict_of_tuples = {('a', 'b'): 1, ('c', 'd'): 2}

# Main dictionary with dictionary of tuples as keys
main_dict = {dict_of_tuples: 'value'}

print(main_dict)  # Output: { {('a', 'b'): 1, ('c', 'd'): 2}: 'value' }

These examples demonstrate that dictionaries can indeed serve as keys in other dictionaries in Python.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!