Dictionaries
• We can use any datatypes for values. For example, a value can be a number, string, list,
tuple or another dictionary.
• But keys should obey the following rules:
Keys should be unique. It means, duplicate keys are not allowed.
• If we enter same key again, the old key will be overwritten and only the new key will be
available.
• Keys should be immutable type. For example, we can use a number, string or tuples as
keys since they are immutable.
• We cannot use lists or dictionaries as keys. If they are used as keys, we will get
‘TypeError’.
Adding Keys & Replacing Values
• We can modify the existing value of a key by assigning a new value as:
dict[‘Salary’] = 10500.00
• We can also insert a new key-value pair into an existing dictionary, by mentioning the key
and assigning a value to it as: dict['Dept'] = 'Finance’
• This pair is not added at the end of existing pairs. It may be added at any place in the
dictionary.
Accessing Values from Dictionaries
• To access the value associated with a key, mention the key name inside the square
braces, as: dict[‘Name’].
• This will return the value associated with ‘Name’.
Accessing Values from Dictionaries
Removing Keys from Dictionaries
• We can delete a key-value pair from the dictionary using del statement as: del
dict['Id’]
• To test whether a ‘key’ is available in a dictionary or not, we can use ‘in’ and ‘not in’
operators. These operators return either True or False.
Traversing a Dictionary
Traversing a Dictionary
Dictionary Methods
• Various methods
are provided to
process the
elements of a
dictionary.
• These methods
generally retrieve
or manipulate
the contents of a
dictionary.
A Python program to retrieve keys, values and key-value pairs from a dictionary.
PRACTICE PROGRAM: A Python program to create a dictionary from keyboard and
display the elements.
A Python program to
create a dictionary with
cricket players names
and scores in a match.
Also we are retrieving
runs by entering the
player’s name.
Using for Loop with Dictionaries
A Python program to
show the usage of for
loop to retrieve elements
of dictionaries.
Using for Loop with Dictionaries
• get() method is
used on a
dictionary to
retrieve the value
by giving the key.
• If the key is not
found in the
dictionary, then
it returns some
default value.
Using for Loop with Dictionaries
• get() method is used on a dictionary to retrieve the value by giving the key.
• If the key is not found in the dictionary, then it returns some default value.
Sorting the elements of Dictionary using Lambdas
• Let’s take an example dictionary as:
colors = {10: "Red", 35: "Green", 15: "Blue", 25: "White"}
• Suppose we want to sort this dictionary into ascending order of keys, i.e. on
color codes, we can use sorted() function in the following format:
sorted(elements, key = color code)
• Elements of the dictionary can be accessed using the [Link]() method.
• A key can be prescribed using a lambda function as:
key = lambda t: t[0]
Sorting the elements of Dictionary using Lambdas
Converting Lists into Dictionary
• When we have two lists, it is possible to convert them into a dictionary.
• There are two steps involved to convert the lists into a dictionary.
• The first step is to create a ‘zip’ class object by passing the two lists to
zip() function as: z = zip(countries, cities)
• The zip() function is useful to convert the sequences into a zip class
object.
• There may be 1 or more sequences that can be passed to zip() function.
• The second step is to convert the zip object into a dictionary by using
dict() function as: d = dict(z)
• Here, the 0th element of z is taken as ‘key’ and 1st element is converted
into its ‘value’ and so on.
Converting Lists into Dictionary
A Python program to
convert the elements
of two lists into key-
value pairs of a
dictionary.
zip(countries, cities): pairs u
elements from both lists by inde
into tuples.
dict(z) — converts those tuple
into key-value pairs, wher
countries become the keys an
cities become the values.
Converting Strings into Dictionary
• When a string is given with key and value pairs separated by some
delimiter (or separator) like a comma ( , ) we can convert the string into
a dictionary and use it as dictionary.
• First, we should split the string into pieces where a comma is found
using split() method and then break the string at equals ( = ) symbol as:
for x in [Link](','):
y= [Link]('=')
• Each piece of the string is available in ‘y’.
• The second step is to store these pieces into a list ‘lst’ using append()
method as: [Link](y)
• The third step is to convert the list into a dictionary ‘d’ using dict()
function as: d = dict(lst)
Converting Strings into Dictionary
A Python
program to
convert a string
into key-value
pairs and store
them into a
dictionary.
Passing Dictionaries to Functions
• We can pass a dictionary to a function by passing the name of the dictionary
• This function fun() is taking ‘dictionary’ object as parameter. Using for loop, we are displaying
the key – value pairs of the dictionary.
A Python function to accept a dictionary and
display its elements.
Default Dictionary
• With a regular dict, accessing a missing key raises a KeyError
• defaultdict is a subclass of the built-in Python dictionary (dict) provided by the collections
module.
• A defaultdict works like a normal dictionary, but it automatically assigns a default value to a
key that does not exist yet.
• This saves you from manually checking if a key is present
• SYNTAX:
• default_factory decides the default value type:
int → default = 0
list → default = []
set → default = set()
Default Dictionary
Ordered Dictionaries
• The elements of a dictionary are not ordered.
• It means the elements are not stored into the same order as they were entered
into the dictionary.
• An ordered dictionary is a dictionary but it will keep the order of the elements.
• The elements are stored and maintained in the same order as they were entered
into the ordered dictionary.
• We can create an ordered dictionary using the OrderedDict() method of
‘collections’ module.
• So, first we should import this method from collections module,
from collections import OrderedDict
• Once this is done, we can create an ordered dictionary with the name ‘d’ as:
d = OrderedDict()
Ordered Dictionaries
• A Python program to create a dictionary that does not change the order of
elements.
Counter
• A counter is a special dictionary that keeps track of number of
times each item appears.
• The items are the keys, and their counts are the values.
Common Methods of Counter
• most_common(n): Returns n most frequent elements
• elements(): Returns elements based on count
Eg: list([Link]())
Counter