Xi - Dictionary
Xi - Dictionary
Class : XI (2024-25)
ShriKant Yadav
PGT (Info. Pract.)
Chapter : 5
Dictionary in Python
Introduction
• Python provides us various options to store multiple
values under one variable name.
• Dictionaries is also a collection like a string and list.
• It is a very versatile data type.
• There is a key in it with a value.(Key:value)
• Dictionaries are mutable data types and it is an
unordered collection in the form of key:value
• In List, index of a value is important whereas in
dictionary, key of a value is important.
Dictionary Creation
• To create a dictionary, it is needed to collect pairs of
key:value in “{ }”.
•<dictionary-name>={ <key1>:<value1>,<key2>:<value2>,<key3>:<value3>. . . }
Example:
teachers={“Rajeev”:”Math”, “APA”:”Physics”,”APS”:”Chemistry:”SB”:”CS”}
In above given example :
teachers={“Rajeev”:”Math”, “APA”:”Physics”,”APS”:”Chemistry:”SB”:”CS”}
<dictionary>[<key>] = <value>
By passing List
Nesting in Dictionary
look at the following example carefully in which element of a dictionary is
a dictionary itself.
Updation in a Dictionary
following syntax is used to update an element in Dictionary-
<dictionary>[<ExistingKey>]=<value>
WAP to create a dictionary containing names of employee as key and their salary as
value. Output
Deletion of an element from a Dictionary
following two syntaxes can be used to delete an element form a
Dictionary. For deletion, key should be there otherwise python
will give error.
1. del <dictionary>[<key>]- it only deletes the value and
does not return deleted value.
False
json.dumps(<>,indent=<n>)
Program to create a dictionary by counting words in a line
Here a dictionary is
created of words
and their frequency.
Dictionary Function and Method
1. len( ) Method : it tells the length of dictionary.
In the above given example, you can see that change is done in
the values of similar keys whereas dissimilar keys got joined with
their values.