4.10.Python Dictionary
4.10.Python Dictionary
INTRODUCTION: Dictionary
Key-value pair
Creating A Dictionary
Iterating Through A Dictionary
Deleting Dictionary Elements
Built-in Dictionary Functions
INTRODUCTION: Dictionary
A dictionary is like a list, but more in general. In a list, index value is an integer, while in a
dictionary index value can be any other data type and are called keys. The key will be used
as a string as it is easy to recall. A dictionary is an extremely useful data storage construct
for storing and retrieving all key value pairs, where each element is accessed (or indexed) by
a unique key. However, dictionary keys are not in sequences and hence maintain no left-to
right order.
It is an un-ordered collection of items where each item consist of a key and a value. It is
mutable (can modify its contents ) but Key must be unique and immutable. Dictionary is also
known as associative array or mapping or hashes .
Key-value pair
We can refer to a dictionary as a mapping between a set of indices (which are called keys)
and a set of values. Each key maps a value. The association of a key and a value is called a
key-value pair.
Syntax:
Example
A={1:"one",2:"two",3:"three"}
print A
output:
Creating A Dictionary
It is enclosed in curly braces {} and each item is separated from other item by a comma(,).
Within each item, key and value are separated by a colon (:).
Example: -
#Accessing an Item
OUTPUT
Example: -
OUTPUT
Informatics practices 11
Example: -
OUTPUT
del, pop() and clear() statement are used to remove elements from the dictionary.
del
Example: -
Output
(‘before del’, {‘Class’: 11, ‘Subject’: ‘Informatics Practices’}) (‘after item delete’, {‘Subject’:
‘Informatics Practices’}) (‘after dictionary delete’, )
pop() method is used to remove a particular item in a dictionary. clear() method is used to
remove all elements from the dictionary.
Example: -
Output
(‘before del’, {‘Class’: 11, ‘Subject’: ‘Informatics Practices’}) (‘after item delete’, {‘Subject’:
‘Informatics Practices’}) (‘after clear’, {})