×

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.


Related Topics

Python Kwargs Example

In this article, we'll talk about Python's kwargs notion. In Python, kwargs has two stars and passes a variable number of keyworded argument lists to the function, whereas args has...

5 minutes read.

How to Parse JSON in Python

JSON The JSON, the Java Script Object Notation, is an open standard file designed for data interchange; it is light-weighted text. The JSON uses human-readable text to store and transmit the...

4 minutes read.

Anaconda in Python 3

What is Anaconda in Python 3? Anaconda is an open-source package combining Python and R programming languages used for data analytics and processing data. It consists of a huge number of...

4 minutes read.

Subprocess in Python

In this tutorial, we will understand what is a subprocess in python and will understand how to use it. Subprocess A subprocess is a very prevailing portion of the python library. It...

3 minutes read.

Python List Size

Introduction The list data type in Python is an ordered, flexible collection. A list may also contain duplicate entries. To get the size of any object, use the len() function in...

6 minutes read.

Reverse a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Python System Command

To execute a program in Python, we need to execute some shell commands to run our program on the computer. Python will provide some shell commands in our background to...

3 minutes read.

Poolmanager in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

GUI Calculator in Python

Introduction In Python, we can develop a GUI(Graphical User Interface) with multiple options. It offers us some great and commonly used methods for the development of the Graphical User Interface. Tkinter...

4 minutes read.

Python Syntax

Python is a strong object-oriented programming language that is simple to learn. Python was created to be a very readable programming language. The syntax of the Python programming language is...

8 minutes read.

Python List copy() method

Python List copy () method The list.copy () method returns a shallow copy of the list. Syntax list.copy() Parameter NA Return This function returns the copy for the given list. Example 1 # Python program explaining # the list.copy() method # passing the...

1 minute read.

XXhash Python Examples

XXhash Python: xxHash is an extremely rapid hash calculation that operates inside the confines of RAM. Code is incredibly convenient, and hashes (almost nothing/large endian) are same at all levels. Execution of...

4 minutes read.

Python set()

Python set() Class The set() class in Python returns a new set object, optionally with elements taken from iterable.  Syntax class set([iterable]) Parameter iterable : This parameter represents a sequence, collection or an iterator object Return This function returns a...

1 minute read.

tell() function in Python

Introduction The tell() function in Python is used to return the current position of the file read/write pointer within the file. An integer value is returned by this method, and it...

2 minutes read.

Returning Multiple Values in Python

Python is considered a general-purpose programming language; it is a high-level programming language that is not much difficult and easier to learn. It is rich in libraries that can be...

3 minutes read.

Python program to add two number

Python program to add two number This program will add the two numbers and display their sum on the screen. Example: Input: Number1 = 20        Number2 = 30   Output: Sum =...

2 minutes read.

Python Time Module

Python contains many files that can be imported into a python code and used whenever we want. One of that modules is the time module. It is a good practice...

6 minutes read.

Python Random Module

The tutorial for the Python random module demonstrates how to produce pseudo-random integers in Python. Random Number Generator (RNG) The RNG (random number generator) generates a series of values with no discernible...

8 minutes read.

How to Make an App with Python

In this age of mobiles, rapid mobile application development has got a lot of traction. Moreover, app developers are high in demand because of the increase in digitization. Generally, Python is...

4 minutes read.

Python Tricks: The Book

A Buffet of Awesome Python Features Dan Bader is the author of the book called Python Tricks . he is the owner and editor of Real Python and one of the...

3 minutes read.