×

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

Image to NumPy Arrays in Python

Image is a simple process of working model confined to machine learning, Python works with the image in the data format of width and height i.e. Images are excelled into...

3 minutes read.

Python program for perfect number

Python program for perfect number Before writing any program for a given problem, we have to understand the problem for which we are creating a solution program. So, let's understand what...

2 minutes read.

Python program to print calendar

Python program to print the calendar This article will explain how to print the calendar of month and year using Python's calendar module. It's a straightforward thing in Python by importing...

1 minute read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

How to Install Numpy in PyCharm

What is PyCharm? JetBrains created the hybrid platform known as PyCharm as a Python IDE. The Python IDE PyCharm is used by some major companies, including Twitter, Facebook, Amazon, and many...

4 minutes read.

Google Python Class

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....

3 minutes read.

Python Continue Statement

In Python, loops automate and repeat processes in a cost-effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration, or ignore the...

3 minutes read.

How to append a string in python

Adding or appending a string to another string is easy in Python. It is called concatenation and is a basic concept of strings in almost all programming languages. Ways to Append...

4 minutes read.

Python Logistic Regression with Sklearn & Scikit

In this article, we'll walk through a tutorial for utilising the Python Sklearn (formerly known as Scikit Learn) package to implement logistic regression. To assist you in remembering the concept,...

18 minutes read.

Python Support

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....

3 minutes read.

Python String isupper() method

Python String isupper() method The String.isupper() method in Python returns a boolean value ‘true’ if all cased characters in the string are uppercase else for any other value is returns false. Syntax String.isupper() Parameter NA Return This...

2 minutes read.

Latest Project Ideas using Python 2024

Python is one of the well-known languages for programming in the contemporary domain of computer science. The demand to adopt Python for IT purposes is steadily increasing because of its...

7 minutes read.

Python String center() method

Python String center() method The center() method will center align the string, using a specified character (space is default) as the fill character. Syntax string.center(width[, fillchar]) Parameter width This parameter represents the length of the returned string. fillchar...

1 minute read.

Accuracy_score Function in Sklearn

A crucial stage in data science is measuring our model's performance using the appropriate metric. In this article, we will examine two methods for calculating the accuracy of your predictions:...

13 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

Classes & Objects in Python

Classes and Objects are used in most modern programming languages, mainly in Object-oriented Programming languages. What is meant by Object Oriented Programming language? Usage of objects and their components in order to...

7 minutes read.

IPython Display

A command shell, often known as IPython is a software application that makes an operating system's features accessible to users or other applications. Based on the purpose and specific functioning...

6 minutes read.

The Calendar Module of Python

The calendar module provides calendar features, including printing functions for a specific month or year. Default is the first day of the week on Monday and the last day on Sunday...

3 minutes read.

Merge Sort using Python

Merge Sort is a technique that is used for sorting elements in an array using a special method known as divide and conquer. It is the best example of the...

5 minutes read.