In this post, you will learn what is dictionary, how to implement a dictionary in python, loop in the dictionary, methods of the dictionary, and so on.

So let’s start learning python dictionaries in detail.

What is Dictionary in python?

A dictionary is a built-in data structure in python and it is used to store an unordered collection of items in the form of a key: value pair.

OR you can say, that dictionary is an unordered collection of data in a key: value pair.

Syntax of Python Dictionary

key of dictionary is always unique and value may or may not be unique.

Why we use dictionary?

Due to the limitations of a list, list is not sufficient to represent real-life data.

Create a dictionary

there are two ways to create a dictionary in python.

  1. using curly brackets ‘{ }
  2. using dict() function

Create a dictionary using curly brackets.

To create a dictionary in Python write comma-separated data in the form of a key: value pair inside the curly bracket.

Example:

name = {'name':'saurabh','age':19,'collage':'unknown'}
print(name)

Output:

{'name': 'saurabh', 'age': 19, 'collage': 'unknown'}

Create a dictionary using dict() function.

You can also use the dict() function to create a dictionary in Python. let’s see it with the help of an example.

user1 = dict(name = "ibrahim",age = 20,collage = "unknown")
print(user1)

Output:

{'name': 'ibrahim', 'age': 20, 'collage': 'unknown'}

When you create a dictionary using the dict() function, write key = value (int, list, float, tuple, etc..).

Access data from the dictionary

With the help of keys, you can access the data of a dictionary because a dictionary is an unordered collection of data and there is no indexing.

write a square bracket after the name of the dictionary and inside a square bracket write your key to get the value of a specified key. If a key is not present in your dictionary it will give an error.

user1 = dict(name = "yash",age = 20,collage = "unknown")
print(user1['name']) # yash
print(user1['gender']) # error

Output:

yash
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(user1['gender'])
KeyError: 'gender'

get() method

You can also use the .get() method to access data from the dictionary and it will not give an error if the key is not present in the dictionary.

Example:

user1 = dict(name = "yash",age = 20,collage = "unknown")
print(user1.get('age')) # 20
print(user1.get('gender')) # None

Output:

20
None

By default, the .get() method returns None if the key is not found, but you can also print custom text if you want. Just add a comma after specifying the key within the .get() method and pass your custom text.

user1 = dict(name = "yash",age = 20,collage = "unknown")
print(user1.get('age')) # 20
print(user1.get('gender','Not Found'))

Output:

20
Not Found

Which type of data a dictionary can store?

You can store anything (number, string, list, dictionary, tuple, etc.) inside a dictionary.

Example:

user_info = {
    'name': 'ram',
    'age': 24,
    'fav_movie': ['coco','dolittle'],
    'fav_tune': ['awakening','fairy tale']
}
print(user_info)
print(user_info['fav_movie'])

Output:

{'name': 'ram', 'age': 24, 'fav_movie': ['coco', 'dolittle'], 'fav_tune': ['awakening', 'fairy tale']}
['coco', 'dolittle']

Add data in the dictionary

Let’s understand how to add data in the dictionary with the help of an example.

my_info = {} #create empty dictionary
print(my_info) 
my_info['name'] = 'harshit'   #add data to dictionary
my_info['age'] = 25

print(my_info) #data is added in dictionary

Output:

{}
{'name': 'harshit', 'age': 25}

Delete data from a dictionary

There are mainly two methods used to delete data from a dictionary and they are.

  1. pop() method
  2. popitem() method

pop() Method

A pop() method is used to remove the value of a specified key.

syntex –> dictionary_name.pop(key_name)

Example:

number1 = {
    "game":"BGMI",
    "singer":"arjit singh",
    "cricketer":"virat kohli"
}
print("before pop")
print(number1)

number1.pop('singer')

print("after pop")
print(number1)

Output:

before pop
{'game': 'BGMI', 'singer': 'arjit singh', 'cricketer': 'virat kohli'}
after pop
{'game': 'BGMI', 'cricketer': 'virat kohli'}

popitem() method

A popitem() method is used to remove data at the end of the dictionary.

syntex –> dictionary_name.popitem()

Example:

user1 = {'name': 'harshit', 'age': 25, 'state': 'haryana'}
print(user1)

user1.popitem()

print(user1)

Output:

{'name': 'harshit', 'age': 25, 'state': 'haryana'}
{'name': 'harshit', 'age': 25}

Loop in dictionary

before applying the loop let’s see some methods of dictionary that are used with the loop.

  1. .keys() –> gives keys of dictionary
  2. .values() –> gives values of dictionary
  3. .items() –> gives keys and values of the dictionary in the form [(key1, value1),(key2, value2),...]

print keys of dictionary

user_info = {'name': 'yash', 'age': 21, 'state': 'Gujarat'}

for i in user_info:
    print(i)

# ******OR********
# for i in user_info.keys():
#     print(i)

Output:

name
age
state

print values of dictionary

user_info = {'name': 'yash', 'age': 21, 'state': 'Gujarat'}

for i in user_info.values():
    print(i)

Output:

yash
21
Gujarat

print both keys and values of dictionary

user_info = {'name': 'yash', 'age': 21, 'state': 'Gujarat'}

for i,j in user_info.items():
    print(f'{i}:{j}')

Output:

name:yash
age:21
state:Gujarat

check if key exists in the dictionary.

user_info = {'name': 'harshit', 'age': 25, 'state': 'haryana'}

if 'age' in user_info:
    print('age is present')
else:
    print('not present')


if 'surname' in user_info:
    print('surname present')
else:
    print('surname is not present')
    
    
# You can also use .keys() method to check if key is present or not

if 'age' in user_info.keys():
    print('age is present')
else:
    print('age is not present')

Output:

age is present
surname is not present
age is present

check if value exists in the dictionary.

user_info = {'name': 'yash', 'age': 21}

if 'yash' in user_info.values():
    # .values() method check for values
    print('yash is present')
else:
    print('not present')

Output:

yash is present

methods of dictionary

.update().fromkeys().get()
.pop().popitem().clear()
.copy().items().values()
.keys()setdefault()

update() method

update() method is used to add data in a dictionary but arguments passed in the update method are in the form of a { key: value } pair.

Example:

user_info = {'name': 'yash', 'age': 21, 'state': 'Gujarat'}

Extra_info = {'fav_movie':'dolittle','hobbies':['reading','writing']}

user_info.update(Extra_info)
print(user_info)

Output:

{'name': 'yash', 'age': 21, 'state': 'Gujarat', 'fav_movie': 'dolittle', 'hobbies': ['reading', 'writing']}

fromkeys() method

fromkeys() method is used to create a dictionary with default values.

Example:

dictinary = dict.fromkeys(['name','age','hobbies'],'unknown')
print(dictinary) 

Output:

{'name': 'unknown', 'age': 'unknown', 'hobbies': 'unknown'}

clear() method

clear() method is used to clear data of dictionary.

Example:

info = {'name': 'harshit', 'age': 25}

info.clear()
print(info)

Output:

{}

copy() method

copy() method is used to create a new copy of the existing dictionary.

Example:

info = {'name': 'harshit', 'age': 25}

info2 = info.copy()

print(info2)

Output:

{'name': 'harshit', 'age': 25}

if you write info2 = info, this will not create a new copy of the dictionary but it will only create two different names for your dictionary.

setdefault() method

The setdefault() method is very similar to the get() method, but the setdefault() method creates a new key with a default value if the key is not present in the dictionary.

my_dict = {'a': 1, 'b': 2}

# Using setdefault to set a default value for a key that doesn't exist
result1 = my_dict.setdefault('c', 0)  # 'c' is not in the dictionary, so it's added with a default value of 0
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 0}
print(result1)  # Output: 0

# Using setdefault for a key that already exists
result2 = my_dict.setdefault('a', 10)  # 'a' is already in the dictionary, so its value is not changed
print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 0}
print(result2)  # Output: 1 (the existing value associated with 'a')

Hope this post will help you to learn Python dictionary -thank you

Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

1 Comment

  1. january calendar Reply

    Hi there to every body, it’s my first visit of this weblog;
    this website includes remarkable and actually good stuff designed for
    readers.

Write A Comment