Can a dictionary be a key in another dictionary python?

Class name... OK :/

My solution is to create a class, with dict features, but implemented as a list with {key, value} objects. key and value can be anything then.

class DictKeyDictException(Exception):
    pass


class DictKeyDict():

    def __init__(self, *args):
        values = [self.__create_element(key, value) for key, value in args]
        self.__values__ = values

    def __setitem__(self, key, value):
        self.set(key, value)

    def __getitem__(self, key):
        return self.get(key)

    def __len__(self):
        return len(self.__values__)

    def __delitem__(self, key):
        keys = self.keys()

        if key in keys:
            index = keys.index(key)
            del self.__values__[index]

    def clear(self):
        self.__values__ = []

    def copy(self):
        return self.__values__.copy()

    def has_key(self, k):
        return k in self.keys()

    def update(self, *args, **kwargs):
        if kwargs:
            raise DictKeyDictException(f"no kwargs allowed in '{self.__class__.__name__}.update' method")
        for key, value in args:
            self[key] = value

        return self.__values__

    def __repr__(self) -> list:
        return repr(self.__values__)

    @classmethod
    def __create_element(cls, key, value):
        return {"key": key, "value": value}

    def set(self, key, value) -> None:
        keys = self.keys()

        if key in keys:
            index = keys.index(key)
            self.__values__[index] = self.__create_element(key, value)
        else:
            self.__values__.append(self.__create_element(key, value))

        return self.__values__

    def keys(self):
        return [dict_key_value["key"] for dict_key_value in self.__values__]

    def values(self):
        return [value["value"] for value in self.__values__]

    def items(self):
        return [(dict_key_value["key"], dict_key_value["value"]) for dict_key_value in self.__values__]

    def pop(self, key, default=None):
        keys = self.keys()

        if key in keys:
            index = keys.index(key)
            value = self.__values__.pop(index)["value"]
        else:
            value = default

        return value

    def get(self, key, default=None):
        keys = self.keys()

        if key in keys:
            index = keys.index(key)
            value = self.__values__[index]["value"]
        else:
            value = default

        return value

    def __iter__(self):
        return iter(self.keys())

and usage :

dad = {"name": "dad"}
mom = {"name": "mom"}
boy = {"name": "son"}
girl = {"name": "daughter"}

# set
family = DictKeyDict()
family[dad] = {"age": 44}
family[mom] = {"age": 43}
# or
family.set(dad, {"age": 44, "children": [boy, girl]})
# or
family = DictKeyDict(
    (dad, {"age": 44, "children": [boy, girl]}),
    (mom, {"age": 43, "children": [boy, girl]}),
)

# update
family.update((mom, {"age": 33}))  # oups sorry miss /!\ loose my children

family.set({"pet": "cutty"}, "cat")
del family[{"pet": "cutty"}]  # cutty left...

family.set({"pet": "buddy"}, "dog")
family[{"pet": "buddy"}] = "wolf"  # buddy was not a dog

print(family.keys())
print(family.values())
for k, v in family.items():
    print(k, v)

In Python, a dictionary is an unordered collection of items. For example:

dictionary = {'key' : 'value',
'key_2': 'value_2'}

Here, dictionary has a key:value pair enclosed within curly brackets {}.

To learn more about dictionary, please visit Python Dictionary.


What is Nested Dictionary in Python?

In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary.

nested_dict = { 'dictA': {'key_1': 'value_1'},
                'dictB': {'key_2': 'value_2'}}

Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB. They are two dictionary each having own key and value.


Create a Nested Dictionary

We're going to create dictionary of people within a dictionary.

Example 1: How to create a nested dictionary

people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

print(people)

When we run above program, it will output:

{1: {'name': 'John', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

In the above program, people is a nested dictionary. The internal dictionary 1 and 2 is assigned to people. Here, both the dictionary have key name, age , sex with different values. Now, we print the result of people.


Access elements of a Nested Dictionary

To access element of a nested dictionary, we use indexing [] syntax in Python.

Example 2: Access the elements using the [] syntax

people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])

When we run above program, it will output:

John
27
Male

In the above program, we print the value of key name using i.e. people[1]['name'] from internal dictionary 1. Similarly, we print the value of age and sex one by one.


Add element to a Nested Dictionary

Example 3: How to change or add elements in a nested dictionary?

people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

people[3] = {}

people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['sex'] = 'Female'
people[3]['married'] = 'No'

print(people[3])

When we run above program, it will output:

{'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'}

In the above program, we create an empty dictionary 3 inside the dictionary people.

Then, we add the key:value pair i.e people[3]['Name'] = 'Luna' inside the dictionary 3. Similarly, we do this for key age, sex and married one by one. When we print the people[3], we get key:value pairs of dictionary 3.

Example 4: Add another dictionary to the nested dictionary

people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
          3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'}}

people[4] = {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}
print(people[4])

When we run above program, it will output:

{'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}

In the above program, we assign a dictionary literal to people[4]. The literal have keys name, age and sex with respective values. Then we print the people[4], to see that the dictionary 4 is added in nested dictionary people.


Delete elements from a Nested Dictionary

In Python, we use “ del “ statement to delete elements from nested dictionary.

Example 5: How to delete elements from a nested dictionary?

people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
          3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'},
          4: {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}}

del people[3]['married']
del people[4]['married']

print(people[3])
print(people[4])

When we run above program, it will output:

{'name': 'Luna', 'age': '24', 'sex': 'Female'}
{'name': 'Peter', 'age': '29', 'sex': 'Male'}

In the above program, we delete the key:value pairs of married from internal dictionary 3 and 4. Then, we print the people[3] and people[4] to confirm changes.

Example 6: How to delete dictionary from a nested dictionary?

people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
          3: {'name': 'Luna', 'age': '24', 'sex': 'Female'},
          4: {'name': 'Peter', 'age': '29', 'sex': 'Male'}}

del people[3], people[4]
print(people)

When we run above program, it will output:

{1: {'name': 'John', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

In the above program, we delete both the internal dictionary 3 and 4 using del from the nested dictionary people. Then, we print the nested dictionary people to confirm changes.


Iterating Through a Nested Dictionary

Using the for loops, we can iterate through each elements in a nested dictionary.

Example 7: How to iterate through a Nested dictionary?

people = {1: {'Name': 'John', 'Age': '27', 'Sex': 'Male'},
          2: {'Name': 'Marie', 'Age': '22', 'Sex': 'Female'}}

for p_id, p_info in people.items():
    print("\nPerson ID:", p_id)
    
    for key in p_info:
        print(key + ':', p_info[key])

When we run above program, it will output:

Person ID: 1
Name: John
Age: 27
Sex: Male

Person ID: 2
Name: Marie
Age: 22
Sex: Female

In the above program, the first loop returns all the keys in the nested dictionary people. It consist of the IDs p_id of each person. We use these IDs to unpack the information p_info of each person.

The second loop goes through the information of each person. Then, it returns all of the keys name, age, sex of each person's dictionary.

Now, we print the key of the person’s information and the value for that key.


Key Points to Remember:

  1. Nested dictionary is an unordered collection of dictionary
  2. Slicing Nested Dictionary is not possible.
  3. We can shrink or grow nested dictionary as need.
  4. Like Dictionary, it also has key and value.
  5. Dictionary are accessed using key.

Can a dictionary be a value in a dictionary Python?

Practical Data Science using Python Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Can dictionaries be nested in Python?

In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary. Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB . They are two dictionary each having own key and value.

Can a dictionary set a key?

The frozenset type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.

Can the value associated with a key itself be a dictionary?

The key and value in a dictionary must be an object; however, everything in Python is an object and thus anything can be used as a key or a value. One common pattern is where the value in a dictionary is itself a container such as a List, Tuple, Set or even another Dictionary.