0% found this document useful (0 votes)
3 views

Python_12_Dictionary

The document provides an overview of Python dictionaries, explaining their structure as unordered collections of key-value pairs. It covers how to create, access, modify, and delete dictionary entries, as well as various built-in functions available for dictionaries. Additionally, it includes examples of creating dictionaries from tuples and lists, and demonstrates how to gather input to create dictionaries at runtime.

Uploaded by

mansha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python_12_Dictionary

The document provides an overview of Python dictionaries, explaining their structure as unordered collections of key-value pairs. It covers how to create, access, modify, and delete dictionary entries, as well as various built-in functions available for dictionaries. Additionally, it includes examples of creating dictionaries from tuples and lists, and demonstrates how to gather input to create dictionaries at runtime.

Uploaded by

mansha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

In a general concepts, dictionary means you have an 'index' of words and for each of them there is a

definition. For example, just like a telephone directory or address register, etc.
Python dictionary is an unordered collection of items. While other compound data types have only
value as an element, a dictionary has a key : value pair.
Let us see an example,

Key Value
"ELENA JOSE" 450
Marks "PARAS GUPTA" 467
"JOEFFIN JOSEPH" 480

Here,
- Key PARAS GUPTA with a value 467
- Key ELENA JOSE with a value 450
- Key JOEFFIN JOSEPH with a value 480

Dictionaries are Python’s built-in mapping type. A map is an unordered, associative collection as
you saw in the above key : value pair.
Creating Dictionary
A dictionary can be created in three different ways :
Dictionary using literal notation.
To declare a dictionary, the syntax is:
directory-name = {key : value, key : value, ......, keyN : valueN}
Here,
➢ Dictionary is listed in curly brackets, inside these curly brackets ( { } ), keys and values are declared.
➢ Each key is separated from its value by a colon (:) while each element is separated by commas.
➢ The keys in a dictionary must be immutable objects like strings or numbers.
➢ Dictionary keys are case sensitive.
➢ The values in the dictionary can be of any type.

For example, let us create and print the Marks dictionary:


>>> Marks = {"ELENA JOSE" : 450, "PARAS GUPTA" : 467, "JOEFFIN JOSEPH" : 480}
>>> print (Marks)
{'ELENA JOSE': 450, 'PARAS GUPTA': 467, 'JOEFFIN JOSEPH': 480}

Similarly, let us create another dictionary called Student with following key : value pairs:
>>> Student = { "Name" : "Surbhi Gupta",
"Rollno" : 11,
"Address" : "F2/27 - MIG Flat, Sec-7, Rohini",
"Phone" : "7286798500"
}
>>> print (Student)
{'Name': 'Surbhi Gupta' , 'Rollno': 11 , 'Address': 'F2/27 - MIG Flat, Sec-7, Rohini' , 'Phone': '7286798500'}
Dictionary using dict() function.
The dict( ) function is used to create a new dictionary with no items. For example,
>>> weekdays = dict() # Creates an empty dictionary
>>> print (weekdays) # Prints an empty string with no value
{}
>>> weekdays = dict(Sunday=0, Monday=1, Tuesday=2, Thursday=3)
>>> print (weekdays)
{'Sunday': 0, 'Monday': 1, 'Tuesday': 2, 'Thursday': 3}

Creating empty dictionary using {}.


An empty dictionary can be created using {}. After creating an empty dictionary, we can use square
brackets ( [ ] ) with keys for accessing and initializing dictionary values. For example,
>>> weekdays = {} # an empty dictionary
>>> weekdays[0] = 'Sunday‘ # 0 is the key and ‘Sunday’ is the value
>>> weekdays[1] = 'Monday'
>>> weekdays[2] = 'Tuesday'
>>> print (weekdays) # Prints an empty string with no value
{0: 'Sunday', 1: 'Monday', 2: 'Tuesday'}

Similarly, add remaining weekdays into the dictionary.


>>> print (weekdays)
{0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday'}
Accessing values of dictionary
Using Key Name.
Studdict ={ "Name": "Rohit Sharma",
"Address": "Rohini",
"Fees": 2000
}
You can access the items of a dictionary by referring to its key name, inside square brackets:
Get the value of the "Address" key:
x = Studdict["Address"]
print(x)
Output : Rohini

Using get () method.


There is also a method called get() that will give you the same result:
Get the value of the "Address" key:
x = Studdict.get("Address")
print(x)
Output : Rohini
Iterating through Dictionary
Iterating (or traversing) a dictionary means, process or go through each key of a dictionary with
respective values. When dictionary keys are processed within a loop, the loop variable or a separate
counter is used as key index into the dictionary which prints each key:value elements. The most
common way to traverse the key:value is with a for loop.
For example, let us we have a dictionary with following key – values:

Emp = { "Shika Antony" : "Programmer",


"Aju John" : "Teacher",
"Shreya Rao" : "Teacher",
"Hisham Ahmed Rizvi" : "Programmer",
"Shreya Mathur" : "Accountant",
"Pooja Agarwal" : "Teacher",
"Shivani Behl" : "Programmer"}
To iterate the key : value pair:
>>> for E in Emp:
print (E,":",Emp[E])

Shika Antony : Programmer


Aju John : Teacher
Shreya Rao : Teacher
Hisham Ahmed Rizvi : Programmer
Shreya Mathur : Accountant
Pooja Agarwal : Teacher
Shivani Behl : Programmer
Reeta Sahoo & Gagan Sahoo
You can also use the values() function to return values of a dictionary:

Emp = { }
Emp['Hima John'] = 'Teacher'
Emp['Rohan'] = 'Accountant'
for E in Emp.values():
print (E)

Output
Teacher
Accountant

Loop through both keys and values, by using the items() function:
Emp = { }
Emp['Hima John'] = 'Teacher'
Emp['Rohan'] = 'Accountant'

for x, y in Emp.items():
print(x, ":",y)
Output
Hima John : Teacher
Rohan : Accountant
Modifying & Deleting Dictionary Data
A dictionary value can be modified through the dictionary key. For example, let us first add a new key :
value into the previous Emp dictionary.
>>> Emp['Hima John'] = 'Teacher‘# a key : value added
>>> for E in Emp:
print (E,":",Emp[E])

Shika Antony : Programmer


Aju John : Teacher
Shreya Rao : Teacher
Hisham Ahmed Rizvi : Programmer
Shreya Mathur : Accountant
Pooja Agarwal : Teacher
Shivani Behl : Programmer
Hima John : Teacher

Reeta Sahoo & Gagan Sahoo


Deleting dictionary value using key:

The del statement removes a key-value pair from a dictionary. The dictionary data can only be deleted
using the dictionary key. The syntax is:
del dictionary[key]

Here, the key can be either integer or string. For example, to delete "Hima John" the command is:

>>> del Emp["Hima John"]


>>> for E in Emp:
print (E,":",Emp[E])

Shika Antony : Programmer


Aju John : Teacher
Shreya Rao : Teacher
Hisham Ahmed Rizvi : Programmer
Shreya Mathur : Accountant
Pooja Agarwal : Teacher
Shivani Behl : Programmer

Reeta Sahoo & Gagan Sahoo


Dictionary Functions
A dictionary object has a number of functions and methods. The dot operator (.) is used along with the
string to access string functions except len() and sorted() function.

Description
Function Name = {'Anmol' : 14, 'Kiran' : 15, 'Vimal': 15, 'Amit' : 13, 'Sidharth' : 14, 'Riya' : 14,
'Sneha' : 13}
len() This function gives the number of pairs in the dictionary.
print ("Length : %d" % len (Name)) # prints: Length : 7
copy() This method copy the entire dictionary to new dictionary.
NewName = Name.copy()
print(NewName)
Which prints:
{'Anmol': 14, 'Kiran': 15, 'Vimal': 15, 'Amit': 13, 'Sidharth': 14, 'Riya': 14, 'Sneha': 13}
get() This method returns a value for the given key. If key is not available then it returns default value
None.
print ("Age of Vimal is :", Name.get("Vimal"))
Which prints:
Age of Vimal is : 15
item() This method returns key and value, in the form of a list of tuples — one for each key : value pair.
print ("Names are: ", Name.items())
Names are: dict_items([('Anmol', 14), ('Kiran', 15), ('Vimal', 15), ('Amit', 13), ('Sidharth', 14),
('Riya', 14), ('Sneha', 13)])
Dictionary function continues…
Description
Function Name = {'Anmol' : 14, 'Kiran' : 15, 'Vimal': 15, 'Amit' : 13, 'Sidharth' : 14, 'Riya' :
14, 'Sneha' : 13}
keys() This method returns a list of all the available keys in the dictionary.
print ("Name keys are:", Name.keys())
Which prints:
Name keys are: dict_keys(['Anmol', 'Kiran', 'Vimal', 'Amit', 'Sidharth', 'Riya', 'Sneha'])
values() This method returns a list of all the values available in a given dictionary.
print ("Name values are:", Name.values())
Which prints:
Name values are: dict_values([14, 15, 15, 13, 14, 14, 13])
sorted() This method returns a sorted sequence of the keys in the dictionary.
print(sorted(Name))
Which prints:
['Amit', 'Anmol', 'Kiran', 'Riya', 'Sidharth', 'Sneha', 'Vimal']
update() This method add/merge the content of a dictionary into another dictionary’s key-values pairs.
This function does not return anything. While updating the contents, no duplicated key:value
pair will be updated.
temp = {"Mathew" : 13, 'John' : None} # A new dictionary
Name.update(temp) # Temp dictionary undated/added with Name
print (Name)
Which prints:
{'Anmol': 14, 'Kiran': 15, 'Vimal': 15, 'Amit': 13, 'Sidharth': 14, 'Riya': 14, 'Sneha': 13, 'Mathew':
13, 'John': None}
Dictionary function continues…

Function Description
pop() This method removes the item with key and return its value from a dictionary.
print (Name)
Which prints:
{'Anmol': 14, 'Kiran': 15, 'Vimal': 15, 'Amit': 13, 'Sidharth': 14, 'Riya': 14, 'Sneha': 13, 'Mathew':
13, 'John': None}
Name.pop("Mathew") # returns: 13
print (Name)
Which prints:
{'Anmol': 14, 'Kiran': 15, 'Vimal': 15, 'Amit': 13, 'Sidharth': 14, 'Riya': 14, 'Sneha': 13, 'John':
None}
Name.popitem() # returns: ('Mathew', 13)
print (Name)
Which prints:
{'Anmol': 14, 'Kiran': 15, 'Vimal': 15, 'Amit': 13, 'Sidharth': 14, 'Riya': 14, 'Sneha': 13}
popitem() This method removes key:value pair orderly and it always pops pairs in the same order.
Name.popitem() # returns: ('John', None)
Name.popitem() # returns: ('Sneha', 13)
print (Name)
Which prints:
{'Anmol': 14, 'Kiran': 15, 'Vimal': 15, 'Amit': 13, 'Sidharth': 14, 'Riya': 14}

Reeta Sahoo & Gagan Sahoo


Creating dictionary from tuple:

X = ('Name', 'Rohit Sharma')


Y = ('Address', 'Rohini')
Z = ('Fees', 2000)
a = ( X, Y, Z )
Studdict = dict(a)
print ("Dictionary : ")
print(Studdict)

Output :
Dictionary :
{'Name': 'Rohit Sharma', 'Address': 'Rohini', 'Fees': 2000}

Reeta Sahoo & Gagan Sahoo


Creating List from Tuple and Dictionary from List

a = ('Name', 'Rohit Sharma')


b = ('Address', 'Rohini')
c = ('Fees', 2000)
List = [a, b ,c]
print (" Item 1 of List ",List[0])
print (" Item 2 of List ",List[1])
print (" Item 3 of List ",List[2])

Studdict = dict(List)
print ("Dictionary : ")
print(Studdict)

Output:
Item 1 of List ('Name', 'Rohit Sharma')
Item 2 of List ('Address', 'Rohini')
Item 3 of List ('Fees', 2000)
Dictionary :
{'Name': 'Rohit Sharma', 'Address': 'Rohini', 'Fees': 2000}

Reeta Sahoo & Gagan Sahoo


Giving multiple values with nested tuple

a = ('Name', ('Rohit Sharma','Raman Arora'))


b = ('Address', ('Rohini', 'Ashok Vihar'))
c = ('Fees', (2000,2300))
List = [a, b ,c]
print (" nested item of List ",List[0][1][0])
print (" Item 2 of List ",List[1])
print (" Item 3 of List ",List[2])
Studdict = dict(List)
print ("Dictionary : ")
print(Studdict)

Output:
nested item of List Rohit Sharma
Item 2 of List ('Address', ('Rohini', 'Ashok Vihar'))
Item 3 of List ('Fees', (2000, 2300))
Dictionary :
{'Name': ('Rohit Sharma', 'Raman Arora'), 'Address': ('Rohini', 'Ashok Vihar'), 'Fees': (2000, 2300)}

Reeta Sahoo & Gagan Sahoo


Creating tuple using List and dictionary using list

L = ['Rohit sharma','Raman arora']


a = ('Name', L)
b = ('Address', 'Rohini')
c = ('Fees', 2000)
List = [a, b ,c]

print( "Second element of tuple is ",a[1])


print (" nested item of List ",List[0][1][0])
print (" Item 2 of List ",List[1])
print (" Item 3 of List ",List[2])
Studdict = dict(List)
print ("Dictionary : ")
print(Studdict)

Output:

Second element of tuple is ['Rohit sharma', 'Raman arora']


nested item of List Rohit sharma
Item 2 of List ('Address', 'Rohini')
Item 3 of List ('Fees', 2000)
Dictionary :
{'Name': ['Rohit sharma', 'Raman arora'], 'Address': 'Rohini', 'Fees': 2000}
Reeta Sahoo & Gagan Sahoo
Creating dictionary during runtime

d={}
years = []
month = []
n = int(input("How many records"))

# Creating List of year ad month


for i in range (0,n):
m = int(input("Enter year"))
n = int(input("Enter month"))
years.append(m)
month.append(n)

# Adding List in Dictionary


d["year"] = years
d["month"]=month

print(d)

Reeta Sahoo & Gagan Sahoo


Programs

Program to create a dictionary of number and its square upto n

n = int(input(" Enter a number "))


print( dict([(x, x**2) for x in range(1, n)]))

Finding the frequency of an item in list using dictionary


my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
freq = {}
for item in my_list:
if (item in freq):
freq[item] += 1
else:
freq[item] = 1

for key, value in freq.items():


print ("% d : % d"%(key, value))

Reeta Sahoo & Gagan Sahoo


Programs

Python program to print a dictionary line by line.

students = {'Aex':{'class':'V',
'rolld_id':2},
'Puja':{'class':'V',
'roll_id':3}}
for a in students:
print(a)
for b in students[a]:
print (b,':',students[a][b])

Python script to check if a given key already exists in a dictionary.

d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}


def is_key_present(x):
if x in d:
print('Key is present in the dictionary')
else:
print('Key is not present in the dictionary')
is_key_present(5)
is_key_present(9)
Reeta Sahoo & Gagan Sahoo

You might also like