Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Python Dictionary inbuilt functions
2.1.
get()
2.2.
keys()
2.3.
copy()
2.4.
items()
2.5.
values()
2.6.
pop()
2.7.
update()
2.8.
fromkeys()
2.9.
clear()
3.
Frequently Asked Question's
3.1.
1). Name the different built-in data types in Python language.
3.2.
2). What is the difference between mutable and immutable?
3.3.
3). What do you mean by Dictionaries?
4.
Conclusion
Last Updated: Mar 27, 2024

Methods of Dictionary

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Python is one of the most famous and used programming languages of the coding hub used on a server to create applications.

Here we will be discussing Python data type, i.e., Dictionary. Dictionary are one of the four built-in data types that store the data with different capabilities.

 

Dictionaries store the data like a map in the key: value pairs. Dictionary is represented by curly braces having keys and values. 

 

Example:

 

dict1={ “Name” : “Ashish”, “age” : 20}
print(dict1)

 

Output

{‘Name’ : ‘Ashish’, ‘age’ : 20}

 

Ordered: The current version of the python language, i.e., python 3.7, dictionaries are ordered. This means that the defined order of the items will not change.

Changeable: This means we can modify or change the items after the dictionary has been created.

Does not allow duplicates: Here, this means that the two items cannot have the same key.

 

Python has provided some built-in functions to deal with dictionaries. Let's throw some light on them.

Python Dictionary inbuilt functions

 

get()

This function will return the value for the specified key. The syntax of this function will be:

dict1.get(key, value)

dict1: Name of the dictionary

Key: The name for which the value is to be returned.

Value: If the specified key is not found in the dictionary, the default value, i.e., None, will be returned.

 

Example

Input:

Person = {
  "Name": "Ashish",
  "nationality": "Indian",
  "age": 20
}
y = Person.get("age")
print(y)

 

Output

20

 

If the key is not found in the dictionary, let's see the example.

 

Example

Input:

Person = {
  "Name": "Ashish",
  "nationality": "Indian",
  "age": 20
}

y = Person.get("phone")

print(y)

 

Output

None

 

keys()

This function returns a view object that displays a list of all the keys in the dictionary in order of insertion. The syntax of this function will be:

 

dictionary_name.keys()

It will return all the keys in a given dictionary in the same order as mentioned.

 

Example1

Input:

Student = {
  "Name": "Raj",
  "section": "B",
  "Roll_no": 24
}

t = Student.keys()

print(t)

 

Output

dict_keys(['Name', 'section', 'Roll_no'])

 

 

Example2

We can update the dictionary after the insertion using the update function.

 

Input:

Student = {'Name': 'Raj', 'section': 'B'}

# before updation
print("Keys before Dictionary Updation:")
keys = Student.keys()
print(keys)

Student.update({'Roll_no':37})

# after updation
print(keys)

 

Output

Keys before Dictionary Updation:
dict_keys(['Name', 'section'])
dict_keys(['Name', 'section', 'Roll_no'])

 

copy()

This copy() function will create a copy of the original dictionary. The syntax of the function is as follows:

Dictionary_name.copy()

It will print the dictionary elements as it is mentioned.

 

Example

Input:

Student = {
  "Name": "Raj",
  "section": "B",
  "Roll_no": 24
}

t = Student.copy()

print(t)

 

Output:

{'Name': 'Raj', 'section': 'B', 'Roll_no': 24}

 

items()

This function will return all the items, i.e., all the keys and the dictionary values.

The syntax of this method is as follows:

dictionary_name.items()

It will not take any parameters and return all the tuple pairs in a given dictionary.

 

Example

Input: 

Colors = { 'Color1': 'Blue', 'Color2': 'Green', 'Color3': 'Red' }

Total_items = Colors.items()

# Print all the items present in the Dictionary
print(Total_items)

# update one more pair in the dictionary
Colors.update({'Color4': 'White'});
print('Updated Dictionary will be:')
print(Total_items)

 

Output

dict_items([('Color1', 'Blue'), ('Color2', 'Green'), ('Color3', 'Red')])
Updated Dictionary will be:
dict_items([('Color1', 'Blue'), ('Color2', 'Green'), ('Color3', 'Red'), ('Color4', 'White')])

 

values()

 

This method returns a view object that contains the dictionary's values as a list. The syntax of this function will be:

 

dictionary_name.values()

It will return all the values in a given dictionary.

 

Example 1

Input:

 

Dict1 = {"Name": "Ashish", "Age": "26", "Hello": "5"}
print(Dict1.values())

 

Output

dict_values(['Ashish', '26', '5'])

 

Example 2

Input:

 

Total_costs = {"Cost1" : 700, "Cost2" : 500, "Cost3" : 489}

# total_sum will store all the values of the above dictionary
total_sum = Total_costs.values()
# sum function will calculate the sum of the values 
print(sum(total_sum)) 

 

Output

1689

 

pop()

This function will remove the specified item from the dictionary. The syntax of the function is as follows:

dict1.pop(key, value)

dict1: Name of the dictionary

Key: The name of the item that is to be popped from the dictionary.

Value: If the specified key is not found in the dictionary, the default value, i.e., None, will be returned.

 

Example1

Input:

Dict1 = {"Name": "Ashish", "Age": "26", "Hello": "5"}

Dict1.pop("Age")

print(Dict1)

 

Output

{'Name': 'Ashish', 'Hello': '5'}

 

Example2

Input:

Dict1 = {"Name": "Ashish", "Age": "26", "Hello": "5"}
t = Dict1.pop("Hello")
print(t)

 

Output

5

 

update()

The update() function will insert the key: value pairs in the dictionary. The syntax of this function will be:

Dict1.update(iterable/dictionary)

The update() function parameters could be a dictionary or an iterable key-value pair to insert it in the dictionary.

 

Example

Input:

Colors = {
  "Color1": "White",
  "Color2": "Blue",
  "Color3": "Red"
}

Colors.update({"Color4": "Black"})

print(Colors)

 

Output

{'Color1': 'White', 'Color2': 'Blue', 'Color3': 'Red', 'Color4': 'Black'}

 

fromkeys()

This function will return a dictionary with the specified keys and the specified values. The syntax for this method is as follows:

DICT.fromkeys(keys, value)

Keys: It specifies the keys of the new dictionary.

Value: Default value is none.

 

Example

Input:

x = ('Color1', 'Color2', 'Color3')
y = 0

Dict1 = dict.fromkeys(x, y)
print(Dict1)

 

Output

{'Color1': 0, 'Color2': 0, 'Color3': 0}

 

Example 2

Input:

x = ('Color1', 'Color2', 'Color3')

Dict1 = dict.fromkeys(x)
print(Dict1)

 

Output

{'Color1': None, 'Color2': None, 'Color3': None}

 

clear()

This function will remove all the elements from the dictionary. The syntax for this will be:

dict1.clear()

It will not take any parameters and print an empty list.

 

Example

Input:

Dict1 = {"Name": "Ashish", "Age": "26", "Hello": "5"}
Dict1.clear()

print(Dict1)

 

Output

{}

 

Must Read Python List Operations

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Question's

1). Name the different built-in data types in Python language.

There are four inbuilt data types in Python language, namely:

  • Lists
  • Tuples
  • Dictionaries
  • Sets

 

2). What is the difference between mutable and immutable?

Mutable means that they are liable to change after the creation. Immutable means that they are not liable to change or modify after the insertion. Set and dictionaries are mutable, and tuples are immutable.

 

3). What do you mean by Dictionaries?

A dictionary is a container that stores the data in key-value pairs. Key-value pairs written inside the curly brackets{}, Example: {"num1" : 1, "num2" : 2}

 

Conclusion

In this blog, we have covered the following things:

  • What do you mean by python language?
  • What is the meaning of a Dictionary?
  • Inbuilt methods are used in the dictionary.

 

Anyone interested in learning the python language can enroll in the intuitively designed courses on Coding Ninjas. You can also consider our paid courses such as DSA in Python to give your career an edge over others!

 

Happy Coding!!!

 

Live masterclass