11 Dictionary
11 Dictionary
• DICTIONARIES
Introduction
• Python provides us various options to store multiple
values under one variable name.
• Dictionaries is also a collection like a string, list and
tuple.
• 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
• Assignment
• User entry
• Function
ASSIGNMENT
• 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”}
<dictionary>[<key>] = <value>
By passing List
By passing tuple of a
list
By passing tuple of
tuple
Adding an element
Adding an element in DICTIONARY
in Dictionary
following syntax is used to add an element in Dictionary-
Nesting in Dictionary
look at the following example carefully in which element of a dictionary is
a dictionary itself.
Updating in inaa DICTIONARY
Updation 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 ofofan
Deletion anelement from
element from a Dictionary
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.
STRING LIST TUPLE DICTIONARY