In this article Dictionary in Python we give the information about Dictionary is a data structure that stores key-value pairs in an organized manner. It is used when data has to be accessed on the basis of unique key. It is considered to be an unordered, mutable and indexed collection.

Creating Dictionary

Dictionary is created using {} and each key-value pair is written as key:value.

# A simple dictionary

my_dict = {

    “name”: “Ram”,

    “Age”: 25,

    “Profession”: “Engineer”

}

Main operations of Dictionary

  1. To access

Value is accessed through key.

print(my_dict[“name”]) # Output: RAM

The get() method can also be used:

print(my_dict.get(“age”)) # Output: 25

  1. Adding or Updating a New Key-Value

my_dict[“city”] = “Delhi” #new added

my_dict[“age”] = 30 # updated

print(my_dict)

  1. Deleting a Key or Value

Use pop() method:

my_dict.pop(“profession”)

print(my_dict) # Output: {“name”: “Ram”, “age”: 25, “city”: “Delhi”}

use del:

del my_dict[“city”]

  1. Getting All Keys or Values

print(my_dict.keys()) # Keys: dict_keys([‘name’, ‘age’])

print(my_dict.values()) # Values: dict_values([‘Ram’, 25])

  1. Getting all the items

print(my_dict.items()) # Output: dict_items([(‘name’, ‘Ram’), (‘age’, 25)])

  1. Clearing the Dictionary

my_dict.clear()

print(my_dict) # Output: {}

Iteration in Dictionary

for key, value in my_dict.items():

    print(f”{key}: {value}”)

Dictionary Comprehension

squares = {x: x*x for x in range(1, 6)}

print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Features:

  1. Keys should always be unique and immutable (eg: string, tuple, etc.).
  2. Values ​​can be of any type (mutable or immutable).
  3. It is unordered, meaning the order of the keys has no importance.

Example: student data

students = {

    101: {“name”:”Sita”,”class”:”10th”,”marks”:”85},

    102: {“name”:”Mohan”,”class”:”12th”,”marks”:”92},

}

print(students[101][“Name”]) # Output: Sita

Accessing Values ​​in Dictionary

In Python keys are used to access values ​​from Dictionary. There are several ways to access values ​​in a dictionary. Let us understand this in detail.

  1. Simple Access (By Key)

The value from the dictionary is accessed using direct key.

Syntax:

dictionary_name[key]

Example:

# Dictionary

student = {“name”: “Aman”, “class”: “10th”, “marks”: 85}

# Accessing Value

print(student[“name”]) # Output: Aman

print(student[“marks”]) # Output: 85

  1. By using get() method

get() method is used to access the value safely. If key does not exist, it returns None or a default value.

Syntax:

dictionary_name.get(key, default_value)

Example:

# Dictionary

student = {“name”: “Aman”, “class”: “10th”, “marks”: 85}

# Accessing Value

print(student.get(“Name”)) # Output: Aman

print(student.get(“Age”)) # Output: None

print(student.get(“Age”, “N/A”)) # Output: N/A

  1. Access through Loop

You can access all the values ​​of Dictionary through loop.

Example:

student = {“name”: “Aman”, “class”: “10th”, “marks”: 85}

# getting all values

for key in student:

    print(f”{key}: {student[key]}”)

Output:

Name: Aman

Class: 10th

Points: 85

  1. By using values() method

The values() method returns all the values.

Example:

student = {“name”: “Aman”, “class”: “10th”, “marks”: 85}

# getting all values

print(student.values()) # Output: dict_values([‘Aman’, ’10th’, 85])

# Using as List

for value in student.values():

    print(value)

Output:

Peace

10th

85

  1. Accessing both Key and Value (items() method)

The items() method returns all the key-value pairs of the Dictionary as a tuple.

Example:

student = {“name”: “Aman”, “class”: “10th”, “marks”: 85}

# Accessing key and value together

for key, value in student.items():

    print(f”{key}: {value}”)

Output:

Name: Aman

Class: 10th

Points: 85

Things to note:

  1. While using Key, make sure that the key exists in the Dictionary, otherwise KeyError may occur.
  2. get() is used to avoid error when key is non-existent.
  3. Loop and methods (values() and items()) are very useful for large dictionaries.

Updating dictionary in python:

Updating Dictionary in Python is very easy and flexible. You can add a new key-value to the dictionary, update the value of an existing key, and add multiple key-values.

Main ways to update the dictionary

  1. Adding a New Key-Value

If a given key is not present in the dictionary, then it is considered as a new key and added.

Syntax:

dictionary_name[key] = value

Example:

# Dictionary

student = {“name”:”Sita”,”class”:”10th”}

# Adding new Key-Value

student[“age”] = 15

print(student)

Output:

{‘name’: ‘Sita’, ‘class’: ’10th’, ‘age’: 15}

  1. Updating the value of an existing key

If the given key already exists, its value is updated.

Syntax:

dictionary_name[key] = new_value

Example:

student = {“name”: “Sita”, “class”: “10th”, “age”: 15}

# Updating the Value

student[“class”] = “12th”

print(student)

Output:

{‘name’: ‘Sita’, ‘class’: ’12th’, ‘age’: 15}

  1. Use of update() method

update() method is used to add or update multiple key-values ​​at once.

Syntax:

dictionary_name.update(new_dictionary)

Example:

student = {“name”:”Sita”,”class”:”10th”}

# Use of `update()` method

student.update({“age”: 15, “occupation”: “student”})

print(student)

Output:

{‘name’: ‘Sita’, ‘class’: ’10th’, ‘age’: 15, ‘occupation’: ‘student’}

  1. Checking and updating value based on key

Sometimes we have to first check whether the key exists or not. The in operator can be used for this.

Example:

student = {“name”:”Sita”,”class”:”10th”}

# Checking and updating

if “age” in student:

    student[“age”] += 1

otherwise:

    student[“age”] = 15

print(student)

Output:

{‘name’: ‘Sita’, ‘class’: ’10th’, ‘age’: 15}

  1. Setting the Default Value (setdefault() Method)

setdefault() is used to set the value of the key. If the key already exists, its value is not changed.

Syntax:

dictionary_name.setdefault(key, default_value)

Example:

student = {“name”:”Sita”,”class”:”10th”}

# Setting default value

student.setdefault(“age”, 15)

print(student) # Output: {‘name’: ‘Sita’, ‘class’: ’10th’, ‘age’: 15}

# No change will occur if key exists

student.setdefault(“age”, 18)

print(student) # Output: {‘name’: ‘Sita’, ‘class’: ’10th’, ‘age’: 15}

  1. Adding Multiple Key-Value (Unpacking)

With Python 3.9 and later you can Can use operator.

Example:

student = {“name”:”Sita”,”class”:”10th”}

# Adding new Key-Value

students = students | {“age”: 15, “occupation”: “student”}

print(student)

Output:

{‘name’: ‘Sita’, ‘class’: ’10th’, ‘age’: 15, ‘occupation’: ‘student’}

Headlines:

  1. If the key exists, its value is updated.
  2. If the key does not exist, it is added as a new key.
  3. The update() and setdefault() methods are useful for large dictionaries.
  4. In Python 3.9 Updating Dictionary has become easier using operators.

Delete Dictionary Elements:

There are several methods available to remove elements from a dictionary in Python. You can delete a particular key-value pair, all elements, or the entire dictionary.

Ways to delete elements of Dictionary:

  1. Using pop() method

pop() method is used to delete a particular key and return its value.

Syntax:

dictionary_name.pop(key)

Example:

# Dictionary

student = {“name”: “Aman”, “class”: “10th”, “age”: 15}

# Removing the key

removed_value = student.pop(“class”)

print(student) # Output: {‘name’: ‘Aman’, ‘age’: 15}

print(removed_value) # Output: 10th

  1. Using popitem() method

The popitem() method removes the last added key-value pair and returns it as a tuple.

Syntax:

dictionary_name.popitem()

Example:

student = {“name”: “Aman”, “class”: “10th”, “age”: 15}

# Removing the last element

removed_item = student.popitem()

print(student) # Output: {‘name’: ‘Aman’, ‘class’: ’10th’}

print(removed_item) # Output: (“age”, 15)

  1. Using the del statement

del is used to delete a particular key-value pair or the entire dictionary.

(a) Removing a particular key:

student = {“name”: “Aman”, “class”: “10th”, “age”: 15}

# Removing the key

del student[“class”]

print(student) # Output: {‘name’: ‘Aman’, ‘age’: 15}

(b) Deleting the entire dictionary:

student = {“name”: “Aman”, “class”: “10th”, “age”: 15}

# Deleting the entire dictionary

the student

Note: Trying to access Dictionary after del will throw a NameError.

  1. Using the clear() method

The clear() method removes all the elements of the Dictionary, but the structure of the Dictionary remains intact.

Syntax:

dictionary_name.clear()

Example:

student = {“name”: “Aman”, “class”: “10th”, “age”: 15}

# Removing all elements

student.clear()

print(student) # Output: {}

  1. Checking the presence of the key and removing it

Before deleting it is important to ensure that the key exists.

Example:

student = {“name”: “Aman”, “class”: “10th”}

# Check if key exists or not

if “age” in student:

    del student[“age”]

otherwise:

    print(“Key does not exist.”)

print(student) # Output: {‘name’: ‘Aman’, ‘class’: ’10th’}

Various usage examples:

Removing all key-value pairs and keeping only the structure:

student = {“name”: “Aman”, “class”: “10th”}

student.clear()

print(student) # Output: {}

Removing Dictionary completely:

student = {“name”: “Aman”, “class”: “10th”}

the student

# Now an error will appear on accessing it

Headlines:

  1. pop() and popitem() methods delete only a single key-value.
  2. del can be used to delete a particular key or the entire dictionary.
  3. The clear() method empties the Dictionary, but does not delete it.
  4. Checking the presence of the key is part of secure coding.

Some More: 

POP- Introduction to Programming Using ‘C’

DS – Data structure Using C

OOP – Object Oriented Programming 

Java Programming

DBMS – Database Management System

RDBMS – Relational Database Management System

Join Now: Data Warehousing and Data Mining 

Leave a Reply

Your email address will not be published. Required fields are marked *