dictionary

Dictionary in python

Introduction

This article will discuss a data structure called a dictionary in python. We will also discuss, the creation, updating, modification, accessing, built-in methods, etc with respect to the dictionary.

Definition

Dictionary is a data structure that will hold a list of key-value pairs. Dictionaries are unordered, which means there is no index for dictionaries. We can access a dictionary with the help of keys.

In a dictionary, keys should be unique and values can be repeated.

The syntax for creating a dictionary

variable_name={key1:value1,key2:value2}

Here, the dictionary will be saved in a variable and can be used in the future.

Example

fruit={1:"apple",2:"orange",3:"grapes"}

Here, fruit is a dictionary containing numbers as keys and different fruit as values.

Accessing a dictionary

Method 1

We can access the values of the dictionary with respect to its keys. Keys can be written inside square brackets.

fruit={1:"apple",2:"orange",3:"grapes"}
print(fruit[2])#orange

The above code will retrieve the value of key 2.

Method 2

We can access the keys and values inside a dictionary with the help of for loop as follows,

fruits={1:"apple",2:"orange",3:"grapes"}
for i in fruits:
  print(i)

The above code prints all the keys alone, so if you want to print the corresponding values, you will write as,

fruits={1:"apple",2:"orange",3:"grapes"}
for i in fruits:
  print(i,"-",fruits[i])
1 - apple
2 - orange
3 - grapes

If we need to access the values alone using for loop, we can use,

fruits={1:"apple",2:"orange",3:"grapes"}
for i in fruits.values():
  print(i)

apple
orange
grapes

if we need to access both keys and values at a time can be done using,

fruits={1:"apple",2:"orange",3:"grapes"}
for i,j in fruits.items():
  print(i,"-",j)
1 - apple
2 - orange
3 - grapes

Method 3

We can access the keys and values separately with a built-in function.

fruits={1:"apple",2:"orange",3:"grapes"}
print(fruits.keys())
print(fruits.values())
print(fruits.items())
print(list(fruits.keys()))#Converting all the keys to list data-type explicitly
print(list(fruits.values()))#Converting all the values to list data-type explicitly
print(list(fruits.items()))#Converting all the key value pair to a tupple.
dict_keys([1, 2, 3])
dict_values(['apple', 'orange', 'grapes'])
dict_items([(1, 'apple'), (2, 'orange'), (3, 'grapes')])
[1, 2, 3]
['apple', 'orange', 'grapes']
[(1, 'apple'), (2, 'orange'), (3, 'grapes')]

Adding and modifying elements in a dictionary

It is very easy to add or modify elements in a dictionary

See also  Built-in Functions and Methods in python

Syntax:

Dict[key] = value

Here, 

  • If the key is already available, the value of the key will be changed.
  • If the key is not available, the key-value pair will be added to the dictionary.
fruits={1:"apple",2:"orange",3:"grapes"}
fruits[2]="water melon"
print(fruits)
fruits[4]="kiwi"
print(fruits)
{1: 'apple', 2: 'water melon', 3: 'grapes'}
{1: 'apple', 2: 'water melon', 3: 'grapes', 4: 'kiwi'}

Deleting elements from a dictionary

Method 1 – Use the del keyword

Using the del keyword we can either delete the values or the dictionary itself.

fruits={1:"apple",2:"orange",3:"grapes"}
del fruits[1]
print(fruits)
del fruits
print(fruits)
{2: 'orange', 3: 'grapes'}
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    print(fruits)
NameError: name 'fruits' is not defined

Method 2 – Use pop and popitem

The pop method is used to pop the value to the mentioned key. 

fruits={1:"apple",2:"orange",3:"grapes"}
element=fruits.pop(1)
print(element)
print(fruits)
apple
{2: 'orange', 3: 'grapes'}

The popitem() method removes the item that was last inserted into the dictionary and returns the key-value pair as a tuple.

fruits={1:"apple",2:"orange",3:"grapes"}
element=fruits.popitem()
print(element)
print(fruits)
(3, 'grapes')
{1: 'apple', 2: 'orange'}

Other built-in methods and function

Imagine we have to make the initialisation for all the examples

fruits={1:"apple",2:"orange",3:"grapes"}
NameExplanationExample
clear()Removes all the elements from the dictionary.fruits.clear()print(fruits)#{}
copy()Returns a copy of the dictionary.fruits_copy=fruits.copy()print(fruits_copy)
get()Returns the value of the specified key.print(fruits.get(2))#orange
items()Returns a list containing a tuple for each key value pair.print(fruits.items())#dict_items([(1, ‘apple’), (2, ‘orange’), (3, ‘grapes’)])
keys()Returns a list containing dictionary’s keys.print(fruits.keys())#dict_keys([1, 2, 3])
values()Returns a list containing dictionary’s values.print(fruits.values())#dict_values([‘apple’, ‘orange’, ‘grapes’])
update()Updates the dictionary with the key value pair.fruits.update({4:”water melon”,2:”Kivi”})print(fruits)#{1: ‘apple’, 2: ‘Kivi’, 3: ‘grapes’, 4: ‘water melon’}

Program

fruits={1:"apple",2:"orange",3:"grapes"}
fruits.update({4:"water melon",2:"Kivi"})
print(fruits)
print(fruits.keys())
print(fruits.items())
fruits_copy=fruits.copy()
print(fruits_copy)
element=fruits.popitem()
print(element)
print(fruits)
del fruits[1]
print(fruits)
del fruits
print(fruits)

Output

{1: 'apple', 2: 'Kivi', 3: 'grapes', 4: 'water melon'}
dict_keys([1, 2, 3, 4])
dict_items([(1, 'apple'), (2, 'Kivi'), (3, 'grapes'), (4, 'water melon')])
{1: 'apple', 2: 'Kivi', 3: 'grapes', 4: 'water melon'}
(4, 'water melon')
{1: 'apple', 2: 'Kivi', 3: 'grapes'}
{2: 'Kivi', 3: 'grapes'}
Traceback (most recent call last):
  File "main.py", line 14, in <module>
    print(fruits)
NameError: name 'fruits' is not defined

Practice yourself

  • Write a program to get input from the user and create a dictionary to specify how many times every letter is used.
  • Create a dictionary which the serial number as key and values should be another dictionary that has the student’s name, age, grade, marks in English, maths, science, computer science, total marks, and average marks.
See also  Guess the Number Game

Conclusion

You can fork and use this repl link to explore more about the dictionaries in python. You can write your doubts in the comments and can eagerly expect a reply from your friends. Learning is multiplied by sharing.

Leave a Comment

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

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

we provide projects, courses, and other stuff for free. in order for running we use Google ads to make revenue. please disable adblocker to support us.