What is a dictionary in Python? - Python

What is a dictionary in Python?

Dictionary is one of the sequence data type supported by Python to handle large volume of data Elements in the Dictionary are present in the form of ‘key: value’ pair, where value is the data item and key is the unique Id of value. In Dictionary keys are immutable and values are mutable. In the Dictionary key and value of each element is separated by ‘colon’, elements are separated by ‘comma’ and they are written with curly brackets. By the end of this chapter you will understand the processes like creation and updating the Dictionary, accessing individual elements and traversal of Dictionary, Nesting of Dictionary etc. It also covers Dictionary related Python functions such as-dict(), zip(), del(), pop(), has_key(), items(), len() etc.

Introduction

The DICTIONARY is one of the sequence data type supported by Python. It can be defined as a collection of values of any data type. Unlike List, Tuple and String which have an index number associated with each element, Dictionary have a ‘key: value’ pair. ‘key’ and ‘value’ are separated by colon(:) and pairs are separated by comma.

Here value represents the data item and the key is the unique Id of the value. Like in List we nee to remember the index to access an element, in Dictionary we need to remember the key t access its value. In Dictionary keys are immutable type but the values are mutable type i.e. w can change values of Dictionary in place. A Dictionary is always depicted in curly brackets. Th following are some examples of Dictionary in Python:

{}                                                                                              #Empty Dictionary

{1:’aaa’, 2:’bbb’, 3:’ ccc’}                                                 #Dictionary of names

{‘math: ‘Mr. Puri, ‘science”:”Ms. Patil’}                   #Dictionary of Teachers

How do you declare a dictionary

In Python, the sequence data type Dictionary can be created in two ways”

  1. Creating Dictionary using Assignment method

To create a Dictionary we write the key: value pairs in curly brackets as per following syntax. The keys in the dictionary must be immutable type such as string, number or Tuple with mutable type values.

Syntax

<dictionary name>= {<key>:<value>, <key>:<value>,…}

players = {1: “Sachin”, 2: “Lara”, 3: “ponting”}

print() statement can be used to print the whole Dictionary, as:

Syntax

print(<dictionary name>)

Example

print(players)

What is tuple in Python with example

dictionary in Python with examples?

Write a program to create a Dictionary of monthly sale of 5 salesmen. Use their name as ‘key’ and monthly sales as ‘value’. Also print the dictionary. Sales are; 41000, 39000, 44000, 21500, 32750; and names are- ‘Mohak’, ‘Manan’, ‘Ansh’, ‘Jay’ and ‘Hement’.

msales={‘Manan’:39000, ‘Ansh’:44000,’Jay’:21500, ‘Hement’: 32750}

print(“Monthly Sales Report: \n”, msales)

Creating Dictionary dynamically via keyboard

  1. Using input() statement-

Using input() statement we can feed data for key and value using keyboard to create a Dictionary dynamically. Two input() statements will take input from the user as a key and value of Python Dictionary. Finally a dictionary entry can be created using given below syntax.

<key variable>= input(“<any message>”)

<value variable>=input(“<any message>”)

<dictionary name>[<key variable>]=<value variable>

Write a program to input temperature in 3 cities and create a dictionary using them. Take city name as key and temperature as value.

weather = {}

for a in range(3):

ct=input(“Enter City name:”)

tmp=input(“Enter Temperature:

weather[ct]=tmp

print(“InDictionary is, weather)

For Live Class Watch Our Full Video on you tube by click on the link

How do you access a dictionary in Python?

Python Dictionary is a mutable sequence data type in which elements can be edited in its place Python allow us to access list in both the ways: Whole dictionary at once and Individual element one by one.

 Accessing whole Dictionary

Python Dictionary is a collection of values stored as a ‘key:value’ pair. All elements i.e. keys and es both of dictionary can be displayed on screen by using dictionary name with print() tement

Syntax-1

print(<dictionary name>)

Example

marks (1:38, 2:41, 3:29)

print(marks)

Output

{1:38, 2:41, 3:29}

Explanation

In above example we have created a dictionary of three subject marks with roll number as key and marks as value. When we print the dictionary name, all the elements get printed on screen.

print(“<dictionary name>”)

Syntax-2

Example

Mrktup={(1:38, 2:41, 3:29}

print(*mrktup)

In the above example we have created a dictionary of three subject marks with roll number as key and marks as value. When we print the dictionary name with asterisk sign (*), only the keys get printed on screen without values, bracket and comma.

  1. Accessing individual element or python access dictionary by key

Once a Dictionary is created and elements are stored in it, individual element can be accesses by ting dictionary name followed by key of that element in square bracket in the following mat:

Syntax

<dictionary name>[<key of element>]

Example

marks[1]

Write a program to create a dictionary of marks of five students. Print the whole dictionary, only its keys and marks of the student whose key is entered by the user.

marks={1:39, 2:46, 3:30, 4:37, 5:42}

print(“\nDictionary is = “, marks)

print(“keys of the dictionary is “*marks)

print(“Marks of Roll Number 4”,marks[4])

k=int(input(“\nEnter the roll number of the marks to be displayed: “))

print(“Marks of the”,k,”Roll Numberk is”=marks[k])

Traverse dictionary python example

Accessing and processing each and every element of the Dictionary is called Traversing the Dictionary For traversal of the Dictionary, rather than accessing values using key, we use for loop to access key from the Dictionary and then print its value.

Syntax

for <variable> in <dictionary name>:

                   body of loop

Example

for a in marks:

print(marks[a])

Subscribe Our Youtube Channel For Live Class

https://www.youtube.com/@olevelguruji

Program 61 Write a program to create a dictionary of age of 5 persons. Use Name as key and Age as value. While traversing the dictionary print all its elements and count how many of them are Major and Minor.

mj=mn=0

age ={“Anil” :15, “Sunil”: 28, “Vanil”:12, “Romil”:40,”manzil”:61)

print(“Dictionary elements…”)

for a in age:

print(“Age of”, a, “is”, age[a])

if (age[a]>=18):

             mj=mj+1

else:

            mn=mn+1

print(“\n\nNo. of Major=”, mj)

print(“No. of Minor=”, mn)

Also Check Our Latest Uploads

tuple operations in python with examples

Leave a Comment