Add Dictionary to Dictionary in Python
Dictionary in python:
Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each key-value pair corresponds to a key and its corresponding value. A collection of key-value pairs can be defined as a dictionary by covering it in curly braces (). Each key and the value it corresponds to are separated by a colon (:):
SYNTAX:
SYNTAX:
d = {
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}
Let us consider an example demonstrating the same.
CODE:
mydict =dict([('John','Clark'),('Michael','Stark'),('Ron','Johnson'),('David','Davis'),('James','Bond')])
print(mydict)
OUTPUT:
{'John': 'Clark', 'Michael': 'Stark', 'Ron': 'Johnson', 'David': 'Davis', 'James': 'Bond'}
The following definition of mydict is yet another. Python's version of a dictionary functions similarly to an actual dictionary. The key-values of a dictionary can be repeated and of any type, but the keys must be distinct and of an immutable data type, such as Strings, Integers, and tuples. It is possible to specify key values as keyword arguments if they are just plain strings. When the key is known, dictionaries are designed to retrieve values quickly. The declaration of a dictionary object is as follows. Example: Capitalization: "USA": "Washington D.C.," "France": "Paris," "India": "New Delhi" Key-value pairs are contained inside the dictionary object capitals, which is shown above. { }
CODE:
mydict =dict(John = 'Clark', Michael = 'Stark', Ron = 'Johnson', David = 'Davis', James = 'Bond')
print(mydict)
OUTPUT:
{'John': 'Clark', 'Michael': 'Stark', 'Ron': 'Johnson', 'David': 'Davis', 'James': 'Bond'}
The dictionary's entries appear in the order in which they were defined. But in terms of getting them back, that is irrelevant. No numerical index is used to access dictionary elements. Although the sequence of items inside a dictionary is not necessary for access, Python does ensure that the sequence of items inside a dictionary is maintained. When items are displayed, they do so in the defined order, and the keys are iterated in the same order. A dictionary is expanded at the very end. If items have been deleted, the remaining items' order is preserved.
Traceback (most recent call last):
File "D:\My Portfolio\test.py", line 3, in <module>
print(mydict[2])
KeyError: 2
A simple code for the inbuilt dictionary function uses the clear function to clear the entire dictionary elements.
CODE:
mydict =dict(John = 'Clark', Michael = 'Stark', Ron = 'Johnson', David = 'Davis', James = 'Bond')
print(mydict.clear())
print(mydict)
OUTPUT:
None
{}
Similarly, many in-built functions are available in python dictionaries which are d.get(), d.items(), d.keys(), d.values(), d.pop(), d.popitem(), and d.update().
Nested Dictionary(Add Dictionary to Dictionary):
Let us now understand how to add a dictionary to the dictionary using an example:
EXAMPLE:
Dict = { 'D1': { },'D2': { }}
print("Nested dictionary 1-")
print(Dict)
# same-keys nested dictionaries
Dict = { 'D1': {'name': 'Ron', 'age': '21'}, 'D2': {'name': 'John', 'age': '25'}}
print("\nNested dictionary 2-")
print(Dict)
# Dictionary nested with mixed dictionary keys
Dict = { 'D1': {1: 'K', 2: 'F', 3: 'C'},'D2': {'Name': 'Ken', 1: [1, 2]}}
print ("\nNested dictionary 3-")
print(Dict)
OUTPUT:
Nested dictionary 1-
{'D1': {}, 'D2': {}}
Nested dictionary 2-
{'D1': {'name': 'Ron', 'age': '21'}, 'D2': {'name': 'John', 'age': '25'}}
Nested dictionary 3-
{'D1': {1: 'K', 2: 'F', 3: 'C'}, 'D2': {'Name': 'Ken', 1: [1, 2]}}
There are numerous methods for adding elements to the nested Dictionary. Nested dict[dict][key] = "value" is such a way to add a dictionary by adding values one by one. Adding the entire dictionary at once can also be done by using the formula Nested dict[dict] = "key": "value".
CODE:
Dict = { }
print("Initial nested dictionary:-")
print(Dict)
Dict['D1'] = {}
# progressively adding elements
Dict['D1']['name'] = 'alice'
Dict['D1']['age'] = 22
print("\nAfter adding dictionary D1")
print(Dict)
# Adding the entire dictionary
Dict['D2'] = {'name': 'Amy', 'age': 23}
print("\nAfter adding dictionary D1")
print(Dict)
OUTPUT:
Initial nested dictionary:-
{}
After adding dictionary D1
{'D1': {'name': 'alice', 'age': 22}}
After adding dictionary D1
{'D1': {'name': 'alice', 'age': 22}, 'D2': {'name': 'Amy', 'age': 23}}
Use the indexing [] syntax to get the value of any key in a nested dictionary.
CODE:
Dict = { 'Dict1': {'name': 'Nanny', 'age': '29'},
'Dict2': {'name': 'Bobby', 'age': '19'}}
# prints the value associated with the key "name" in Dict1.
print(Dict['Dict1']['name'])
# prints the value associated with the Dict2 key "age."
print(Dict['Dict2']['age'])
OUTPUT:
Nanny
19
Some of the most popular Python types are dictionaries and lists. They vary in how their elements are accessed, despite sharing several similarities, as you have seen. Dictionary elements can be accessed by key, while list elements can be found using a statistical index based on their order. Lists and dictionaries are typically more appropriate in certain situations than others because of this distinction. By this time, you ought to tell which approach would be the most suitable in any given circumstance.