Humanities/Arts Exam  >  Humanities/Arts Notes  >  Computer Science for Class 11  >  Dictionaries in Python

Dictionaries in Python | Computer Science for Class 11 - Humanities/Arts PDF Download

Introduction


As we have used the English dictionary. It contains different words with its meanings. In python, the dictionary refers to the mapped items using key-value pairs. It is a versatile type of python.
A dictionary item doesn’t contain any index just like list or tuple. Every element in dictionary is mapped with key-value pair. The dictionary element can be referred to a key with the associated value.

What is a dictionary?


Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs the associate keys to value. – Textbook Computer Science with Python, Sumita Arora.
In the dictionary, a key is separated from values using colon (:) and the values with commas.

Creating a Dictionary


To create a dictionary follow this syntax:

<dictionary-object> = {<key>:<value>,<key:value>,.....}

According to the syntax

  • <dictionary-object>: It is just like a variable, referred as dictionary object
  • =: As usual, it is assignment operator
  • {}: The curly braces are used to write key-value pairs inside
  • key: Value pair: The items or elements of dictionary object will be written in this way

Points to remember
While creating a dictionary always remember these points:

  • Each value is separated by a colon
  • The keys provided in the dictionary are unique
  • The keys can be of any type such as integer, text, tuple with immutable entries
  • The values can be repeated
  • The values also can be of any type

Observe the below given examples:

d = {'Mines':'Rajesh Thakare','HR':'Dinesh Lohana','TPP':'Kamlesh Verma','School':'A. Vijayan','Hospital':'Shailendra Yadav'}

d = {1:'Sharda',2:'Champa',3:'Babita',4:'Pushpa',5:'Chandirka',6:'Meena'}

d = {1:100,2:200,3:300,4:400}

Now understand the key-value pairs:

Dictionaries in Python | Computer Science for Class 11 - Humanities/Arts

Creating an empty dictionary


d = {}
As simple as that we have created an empty lists, empty tuple, you can also create an empty dictionary and manipulate it afterwards.
Dictionaries are also known as associative arrays or mappings or hashes.
After creating a dictionary in comprehensive notes Dictionaries in Python for class 11, now learn how to access the elements of a dictionary using various methods.

Accessing elements of the dictionary


Actually dictionaries are indexed based on their keys. So whenever you want to access the values of it keys are used to access them. Observe the following:

d = {1:'Virat Kohli',2:'Ajinkya Rehane',3:'Subhman Gill'}

#Priting with keys

print(d[1],d[3])

#Printing all values

print(d)

The process of taking a key and finding a value from the dictionary is known as lookup. Moreover, you cannot a access any element without key. If you try to access a value with key doesn’t exist in the dictionary, will raise an error.
Now have a look at the following code:

d = {'Mines':'Rajesh Thakare','HR':'Dinesh Lohana','TPP':'Kamlesh Verma','School':'A. Vijayan','Hospital':'Shailendra Yadav'}

for i in d:

   print(i, ":",d[i])

In the above code you can see the variable i prints the key and d[i] prints the associated value to the key.

d = {'Mines':'Rajesh Thakare','HR':'Dinesh Lohana','TPP':'Kamlesh Verma','School':'A. Vijayan','Hospital':'Shailendra Yadav'}

for i,j in d.items():

   print(i, ":",j)

Here, I have separated the values using two variables in the loop.
You can also access the keys and values using d.keys() and d. values() respectively. It will return the keys, and values in the form of sequence. Observe this code and check the output yourself:

d = {'Mines':'Rajesh Thakare','HR':'Dinesh Lohana','TPP':'Kamlesh Verma','School':'A. Vijayan','Hospital':'Shailendra Yadav'}

print(d.keys())

print(d.values())

Create dictionary using dict() function


A dict() function can be used to create a dictionary and initialize the elements as key:value pair. For example,

pr = dict(name='Ujjwal',age=32,salary=25000,city='Ahmedabad')

print(pr)

You can also specify the key:pair value in following manners:

pr = dict({'name':'Ujjwal','age':32,'salary':25000,'city':'Ahmedabad'})

print(pr)

You can also specify the key-values in the form sequences (nested list) as well. Observe the following code:

pr = dict([['name','Ujjwal'],['age',32],['salary',25000],['city','Ahmedabad']])

print(pr)

Add elements to a dictionary


You can add an element to the dictionary with the unique key which is not already exist in the dictionary. Look at the following code:

pr = dict([['name','Ujjwal'],['age',32],['salary',25000],['city','Ahmedabad']])

pr['dept']='school'

print(pr)

Update an element in a dictionary


To update the element, use a specific key and assign the new value for the dictionary. Observe this code:

d = dict({'name':'Ujjwal','age':32,'salary':25000,'city':'Ahmedabad'})

d['salary']=30000

print(d)

Deleting element from the dictionary


You can delete the elements by using del, pop() and popitem() function. The pop() function we will discuss in another article. Observe the following code for del:

d = dict({'name':'Shyam','age':32,'salary':25000,'city':'Ahmedabad'})

del d['age']

Membership Operator


As you know in and not in operator we have used with list and tuple, similarly used with a dictionary. If the key is present in the dictionary, it will return true otherwise false. Look at the code:

d = dict({'name':'Shyam','age':32,'salary':25000,'city':'Ahmedabad'})

if 'name' in d:

   print("Key found")

else:

   print("Key not found")

if 'Shyam' in d.values():

   print("Value found")

else:

   print("Value not found")

Printing dictionary with indentation


To print the dictionary with indentation, you need to import json package. The import json should be written on top of the program and then use json.dumps() function to provide indentation. This function accepts two parameters: dictionary object and indent

Consider this example:

import json

d={'Virat':45,'Rehane':56,'Pujara':76,'Rahul':34}

print(json.dumps(d,indent=3))

Install json using pip insall json command.
Observe the output yourself.

Counting frequency of elements in a list using dictionary


Sometimes users need to calculate the frequency of elements in sequence such as lists. This can be done by following these steps:

  • Create an empty dictionary
  • Take up an element from the list
  • Check if this element exists as a key in the dictionary

Observe the following code:

import json

c=0

txt="This is a text This text is accepted by user input \

User input is given thorugh input() function."

w=txt.split()

d={}

for i in w:

   key = i

   if key not in d:

      c=w.count(key)

      d[key]=c

print("Frequency",w)

print(json.dumps(d,indent=1))

Dictionaries in Python | Computer Science for Class 11 - Humanities/Arts

Dictionary methods


In this section of Dictionaries in Python for class 11, we are going to discuss some built-in functions used with dictionaries. Here we go!

len()


It is used to count the key:value pair from the dictionary. It accepts dictionary objects as a parameter.

d={'Virat':45,'Rehane':56,'Pujara':76,'Rahul':34}

len(d)

The above code will return 4 as there are 4 key:value pairs available in the code.

get()


It is used to get the value of the given key. It accepts two parameters. The first is key and the second is default arguments. The default argument contains an error message if the key is not present in the dictionary. Observe the following key:

d={'Virat':45,'Rehane':56,'Pujara':76,'Rahul':34}

print(d.get('Virat'))

print(d.get('Sachin','Not Found'))

Here, d.get(‘Virat’) returns the value 45 whereas d.get(‘Sachin’,’Not Found’) will return “Not Found” error message.

items()


It is used to get the items presents in the dictionary as a sequence of (key, value) tuples. It will not follow any particular order.

d={'Virat':45,'Rehane':56,'Pujara':76,'Rahul':34}

l=d.items()

for i in d:

   print(i)

The above code will return this output:

('Virat', 45)

('Rehane', 56)

('Pujara', 76)

('Rahul', 34)

keys()


This method returns all the keys of a dictionary in a list form. It will not follow any particular order. Observe this example:

d={'Ramesh':15000,'Suresh':20000,'Akhilesh':21000,'Sameer':22000}

print(d.keys())

The above code will return dict_keys([‘Ramesh’, ‘Suresh’, ‘Akhilesh’, ‘Sameer’]) as output.

values()


It will return values in list form from the dictionary. Just take a look at this:

d={'Ramesh':15000,'Suresh':20000,'Akhilesh':21000,'Sameer':22000}

print(d.values())

The above code will return idct_values([1500,20000,21000,22000]) as output.

fromkeys()


It will return specified keys and values from the dictionary. It accepts two parameters. The first is keys which is mandatory whereas values are optional. The default value is None.

n=int(input("How many customers?"))

l=[]

for i in range(n):

    v=input("Enter names:")

    l.append(v)

d=dict.fromkeys(l,2500)

print(d)

Here dict.fromkeys() method create a dictionary with different keys of names provided into list l with the similar value 2500. Observe this output:

Dictionaries in Python | Computer Science for Class 11 - Humanities/Arts

The fromkeys() method requires an iterable sequence as the first parameter. You cannot pass an integer or a single character. When you do not pass any value as a parameter then it will assign None in front of the key.

setdefault()


It will add an element to the last in the dictionary. It will add key:value. If the given key is not in the dictionary it will add a specified new key:value pair to the dictionary and return added value of the added key otherwise it will be not updated but the current value associated to the specified key is present.
The first parameter of this method is key and second parameter is value.

d={'Ramesh':15000,'Suresh':20000,'Akhilesh':21000,'Sameer':22000}

d.setdefault('Sagar',34000)

If you provide only one parameter, it is considered as key and value will be added None.

update()


update() method will update the element of the dictionary. Observe this code:

d1={'One':10,'Two':20}

d2={'One':30,'Four':40}

d1.update(d2)

print(d1)

It will return {‘One’: 30, ‘Two’: 20, ‘Four’: 40} as output.

copy()


It is used to create a shallow copy of a dictionary. Shallow copy refers to copying upper layers rather than inner objects. The example is as follows:

d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}

d1=d.copy()

It will copy the dictionary one to another. You can use the assignment operator to copy the dictionaries.

d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}

d1=d

pop()


pop() is used to delete an element from the dictionary. It will return the deleted element which has been passed as an argument.
It accepts two parameters. The first parameter is key and the second is a value that will be returned after deletion. if the given key is not found in the dictionary then it will return this. If the value is not specified in pop() method and if the key is not present in the dictionary it will raise KeyeEror.

d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}

  d.pop(2)

The above code will return “Vatsal” as it gets deleted from the dictionary.

d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}

d.pop(5,"Key Not Present")

Here it will give the message Key Not Present. You can delete an element using del keyword as well.

d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}

del d[2]

print(d)

popitem()


This method removes and returns the last key:value pair from the dictionary. It follows the LIFO (Last IN First Out) structure. This method accepts no parameter.

d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}

d.popitem()

Here it will return (4,’Mohan’) as output.

clear()


The clear() method is used to delete all the key:value pairs from the dictionary and makes the dictionary an empty dictionary. It will accept no parameter.

d={1:"Jahan",2:"Vatsal",3:"Vansh",4:"Mohan"}

d.clear()

sorted()


This method is used to sort the specified keys or values. It will accept two parameters: One is the dictionary object and second is the reverse. The default value of reverse is False.

d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}

print(sorted(d))

The above code will return the list of keys as : [2, 4, 11, 30]
If you want to sort keys in descending order use reverse=True. Obseve this:

d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}

print(sorted(d, reverse=True))

The above code output is: [30, 11, 4, 2]
If you want to sort the values it will be used in this manner.

d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}

print(sorted(d.values(), reverse=True))

Observe the result yourself and understand it.
Similarly, you can use the items() method to sort key-value pairs and the answer will be returned in the form of tuples with key-value pairs sorted by keys.

max()


It will return the maximum key or value as specified in the code. Observe this example:

d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}

print(max(d))

print(max(d.values()))

The second line returns 30 and the third line returns ‘Vatsal’.

min()


It will return the minimum key or value as specified in the code. Observe this example.

d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}

print(min(d))

print(min(d.values()))

sum()

It will make the sum of all the specified keys or values. Example:

d={11:"Jahan",2:"Vatsal",30:"Vansh",4:"Mohan"}

print(sum(d))

The document Dictionaries in Python | Computer Science for Class 11 - Humanities/Arts is a part of the Humanities/Arts Course Computer Science for Class 11.
All you need of Humanities/Arts at this link: Humanities/Arts
20 videos|20 docs|5 tests

Top Courses for Humanities/Arts

20 videos|20 docs|5 tests
Download as PDF
Explore Courses for Humanities/Arts exam

Top Courses for Humanities/Arts

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

Free

,

Extra Questions

,

study material

,

Exam

,

Semester Notes

,

Important questions

,

Dictionaries in Python | Computer Science for Class 11 - Humanities/Arts

,

Objective type Questions

,

past year papers

,

Viva Questions

,

MCQs

,

pdf

,

shortcuts and tricks

,

Dictionaries in Python | Computer Science for Class 11 - Humanities/Arts

,

Summary

,

Sample Paper

,

Previous Year Questions with Solutions

,

practice quizzes

,

Dictionaries in Python | Computer Science for Class 11 - Humanities/Arts

,

ppt

,

mock tests for examination

,

video lectures

;