Python Dictionary Tutorial | Create, append Dictionary in python

Last updated Feb 12, 2021

In this python programming tutorial, we are going to learn about the dictionary in python. How to create, use it, how to add or delete items in the dictionary, append elements in dictionary and many more. This brief explanation of the python dictionary will help you in mastering programming. We will also learn about the various built-in methods that will help us in adding and removing elements in the dictionary. Before getting started let's know in brief about what is a dictionary?

 

What is Dictionary in Python?

Dictionary is an ordered collection of items or elements. Each item present in the dictionary has a key pair. When the key is used or called in code, the values present in that appropriate key are retrieved.

In short, dictionaries are used to store values and keys in the syntax of "key: value". It is changeable which means the elements of the dictionary can be changed easily. But it cannot contains duplicate values.

 

Syntax of using Dictionary in python

To create a dictionary in python you have to use the following syntax. Dictionaries are usually written with curly brackets, keys, and values.

 

Syntax:

dictionary_name = {"Key1": "Value1", "Key2": "Value2"}

 

 

How to Create a Dictionary in Python

To create a dictionary in python, we will use the above syntax. In the below example we are going to create a dictionary of properties of Hyundai car. Let's move into the programming section and start our first dictionary program.

Program:

 

# To create the first dictionary

firstDict = {

# Add elements in the form of key:value

"brand": "Hundai",

"model": "I20",

"year": 1999,

"Service": "Lifetime"

}

# Print the created dictionary on the screen

print(firstDict)

 

 

Output:

{'brand': 'Hundai', 'model': 'I20', 'year': 1999, 'Service': 'Lifetime'}

 

 

Add Elements to Dictionary in Python

Dictionaries are mutable which means that we can add or remove new elements in the dictionary very easily. Make sure to add the element in the form of key:value. Let's do one program related to this statement.

 

Program:

 

# To change and adding Elements in Dictionary
my_dict = {'name': 'Robert', 'age': 15}

# To update the age value
my_dict['age'] = 20

# Now the Output will be : {'age': 20, 'name': 'Robert'}
print(my_dict)

# To add item in dictionary
my_dict['address'] = 'Las Vegas'

# Now the Output will be : {'address': 'Las Vegas', 'age': 20, 'name': 'Robert'}
print(my_dict)

 

Output:

{'age': 20, 'name': 'Robert'}                                           

{'age': 20, 'address': 'Las Vegas', 'name': 'Robert'}

 

 

Remove Elements form Dictionary Python

Like adding elements in dictionaries we can also remove the elements from the dictionary. This can be done by using pop() method which helps in removing the value of the inserted key. Also, you can use the popitem() method which will directly remove the item pair from the dictionary. Let's do the program to know more about this

 

# Removing elements from a dictionary

# First create a dictionary
squares = {1: "Python", 2: "Program", 3: "Code", 4: "Beginners"}

# To remove an element, from key 6
print(squares.pop(4))

print(squares)

# To remove an arbitrary element
print(squares.popitem())

print(squares)

# To remove all elements from dictionary
squares.clear()

print(squares)

 

Output:

Beginners                                                               

{1: 'Python', 2: 'Program', 3: 'Code'}                                  

(1, 'Python')                                                           

{2: 'Program', 3: 'Code'}                                               

{}  

 

Dictionary Items

The items or elements present in the dictionary are unordered, changeable, and avoids duplicates. All the elements present in the dictionary are in the form of key: value form. Now as we know about the basics of the dictionary.

You can also use the key to print the value in the dictionary. In the above example let's print the model of the car using the key "model"

 

# To create the first dictionary

firstDict = {

# Add elements in the form of key:value


"brand": "Hundai",

"model": "I20",

"year": 1999,

"Service": "Lifetime"

}

# Print the key "model" value on the screen.

print(firstDict["model"])

 

 

Output:

I20

 

Properties of Dictionary Items

  • Unordered

Above we have mentioned that dictionaries are unordered which means that in dictionaries items cannot have defined order, you can easily identify them by using an index.

  • Changeable

Also, we have discussed that dictionaries are changeable which means we can easily change, modify, add or remove the elements from the dictionary.

  • Duplicates Not Allowed

Dictionaries do not accept duplicates which means that we cannot have 2 items with the same key. If it happens, duplicate values will automatically overwrite the existing values. Here is the program to briefly explain this property

 

Program:

# To create the first dictionary
first_dict = {
# Add elements in the form of key:value

"brand": "Hundai",
"model": "I20",
"year": 1999,
"year": 2000

}
# To print the created dictionary on the screen
print(first_dict)

 

Output:

{'brand': 'Hundai', 'model': 'I20', 'year': 2000}

 

 

Dictionary Length in Python

You can easily determine the length of the dictionary using the len() built-in function in python. To calculate the length of a dictionary we will use the following syntax.

Syntax:

 

print(len(dictionary_name)

 

Here is the python program to briefly explain the above statement.

Program:

 

# To create the first dictionary
first_dict = {

# Add elements in the form of key:value


"brand": "Hundai",
"model": "I20",
"year": 1999,
"Service": "Lifetime",
"colors": ["black", "white", "blue"]

}
# To print the length of dictionary using len() function
print(len(first_dict))

 

Output:

4

 

Dictionary Data Types in Python

 

In the dictionary, we can use all types of data types in python. The values can be of any data type like string, int, boolean and list, etc. Here is an example to explain

first_dict = {

"brand": "Hundai",
"model": "I20",
"year": 1999,
"Service": "Lifetime",
"colors": ["black", "white", "blue"]

}

print(first_dict)

 

 

Output:

{'brand': 'Hundai', 'model': 'I20', 'year': 1999, 'Service': 'Lifetime', 'colors': ['black', 'white', 'blue']}

 

How to check the Type of Dictionary in Python

Dictionaries are stated as objects of data type "dict". To check the type of dictionary we are going to use the type() function in python. It will help us identify the type of class. Here is the program to explain to you everything.

Program:

 

# To create the dictionary

first_dict = {

"brand": "Hundai",
"model": "I20",
"year": 1999,
"Service": "Lifetime",

}
print(type(first_dict))

 

 

Output:

<type 'dict'>

 

Nested Dictionaries

A nested dictionary is a dictionary inside a dictionary or in short words, it is just a collection of dictionaries into 1 single dictionary. Here is the syntax to use nested dictionaries

 

nested_dictionaries = { 'dict1': {'key_1': 'value_1'},

                'dict2': {'key_2': 'value_2'}}

 

 

This diagram will explain to you briefly about nested dictionaries

 

Python Dictionary, Create, append dictionary in python

 

Now we have learned all the topics which are necessary to master the dictionaries in python. To learn more, you have to practice more. We have mentioned some dictionaries examples below which will definitely help you in learning dictionaries in python. Let's start the practice session.

Example 1

 

# To create an empty Dictionary
Dict = {}
print("Sample Dictionary is: ")
print(Dict)

# Now creating a Dictionary with elements with dict() method
Dict = dict({1: 'Python', 2: 'For', 3:'Beginners'})

# To print the dictionary made with dict() method

print("\nDictionary with the use of dict() method: ")
print(Dict)

# Creating a Dictionary including item as a Pair
Dict = dict([(1, 'Python'), (2, 'Programming')])

# To print the dictionary made above

print("\nDictionary with each item as a pair: ")
print(Dict)

 

Output:

Sample Dictionary: {}                                                           
Dictionary with the use of dict() method: {1: 'Python', 2: 'For', 3: 'Beginners'}                                 
Dictionary with each item as a pair: {1: 'Python', 2: 'Programming'} 

 

Example 2

To create a Nested Dictionary

 

Dict = {
1: 'Python', 2: 'For',
3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Python'}}

print(Dict)

 

Output:

{1: 'Python', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Python'}}

Example 3

 

# Python program to demonstrate an element from a Dictionary

# Creating a Dictionary
Dict = {1: 'Python', 'name': 'For', 3: 'Beginners'}

# To access an element using key
print("Accessing an element using the key name:")
print(Dict['name'])

# To access an element using key
print("Accessing an element using key 1:")
print(Dict[1])

 

Output:

Accessing an element using the key name: For                                                                     

Accessing an element using key 1: Python

 

Related Topics

Python Arrays and Different type of Array Examples

Python Strings - Python String Concatination Examples

Python API Integration

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

650 Views