Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
22 views10 pages

Dictionary

This document provides an overview of Python dictionaries, including their features, creation, and various operations such as accessing, adding, updating, and deleting elements. It explains dictionary methods like pop(), popitem(), and clear(), as well as functions like len(), keys(), values(), and get(). The document also covers dictionary membership testing and iteration.

Uploaded by

sheik8610
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views10 pages

Dictionary

This document provides an overview of Python dictionaries, including their features, creation, and various operations such as accessing, adding, updating, and deleting elements. It explains dictionary methods like pop(), popitem(), and clear(), as well as functions like len(), keys(), values(), and get(). The document also covers dictionary membership testing and iteration.

Uploaded by

sheik8610
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

PYTHON DICTIONARIES

LEARNING OBJECTIVES

At the end of this chapter students will be able to understand

Features of dictionaries
Creating a dictionary
Using dict() function
Accessing elements from dictionary
Adding/updating elements
Deleting elements
pop() method
popitem() method
clear() method
Dictionary operations
Dictionary functions

Python dictionary is an unordered collection of items where each item is a key: value
pair. We can also refer to a dictionary as a mapping between a set of keys/indices and a
set of values.

IMPORTANT FEATURES

Each key map to a value. The association of a key and a value is called a key-value pair.
Each key is separated from its value by a colon (:), the items are separated by commas,
and the entire dictionary is enclosed in curly braces.
Keys are unique within a dictionary while values may not be.
The values of a dictionary can be of any type, but the keys must be of an immutable
data type such as strings, numbers, or tuples.
Dictionary is mutable. We can add new items or change the value of existing items.
CREATING A DICTIONARY
A dictionary can be created by placing items (i.e. key-value pair) inside curly braces {}
separated by comma.

SYNTAX

dict1 = {'key1': 'value1','key2': 'value2','key3': 'value3'.......'keyn': 'valuen'}

EXAMPLES

>>> dict1={'R':'RAINY' , 'S':'SUMMER', 'W':'WINTER' , 'A':'AUTUMN'}

>>> print(dict1)

OUTPUT

{'R': 'RAINY', 'S': 'SUMMER', 'W': 'WINTER', 'A': 'AUTUMN'}

EXPLANATION

Here

dict1 is the name of the dictionary

'R', 'S', 'W', 'A' are the keys which maps to 'RAINY', 'SUMMER', 'WINTER', 'AUTUMN' values
respectively.

EXAMPLES

>>> dict2={1: ‘robotics’, 2:’AR’ , 3:’AI’ , 4:”VR’}

>>>dict3={'num':10, 1:20}

>>>dict4={} # empty dictionary


USING dict() FUNCTION

Dictionary can also be created using dict() function

>>>dict5 = dict ({1:'true', 2:'false'})

>>> dict6=dict() # this statement will create an empty dictionary

ACCESSING ELEMENTS FROM DICTIONARY


To access dictionary elements, use the square brackets along with the key to obtain its
value.

>>> print(dict1['R'])

OUTPUT

RAINY

NOTE : An error will occur if we try to access a key which does not exist in a particular
dictionary.

Also, if we try to access the dictionary using its value element, it will result in error.

EXAMPLE

>>> print(dict1['Y']) # Key 'Y' does not exist in dictionary dict1

OUTPUT

Traceback (most recent call last):

File "<pyshell#10>", line 1, in <module>

print(dict1['Y'])

KeyError: 'Y'
>>> print(dict1['RAINY']) # trying to access dictionary using value instead of key

OUTPUT

SyntaxError: unexpected indent

NOTE: More than one entry per key i.e. duplicate key is not allowed in a dictionary. When
duplicate keys are encountered during assignment, the last assignment wins.

EXAMPLE

>>> dict2={'num':10, 1:20, 1:30}

>>> print(dict2[1])

30

Here value, 30 is mapped with key 1 and not 20.

ADDING/UPDATING ELEMENTS

New elements can be added to a dictionary using assignment operator. If the key is
already present, value gets updated, else a new key: value pair is added to the dictionary.

EXAMPLE

>>> dict1={'R':'RAINY' , 'S':'SUMMER', 'W':'WINTER' , 'A':'AUTUMN'}

>>> dict1['C']='CLOUDY' # new element added

>>> print(dict1)

OUTPUT
{'R': 'RAINY', 'S': 'SUMMER', 'W': 'WINTER', 'A': 'AUTUMN', 'C': 'CLOUDY'}

EXAMPLE

>>> dict1['R']='MONSOON' #old value updated

>>> print(dict1)

OUTPUT

{'R': 'MONSOON', 'S': 'SUMMER', 'W': 'WINTER', 'A': 'AUTUMN', 'C': 'CLOUDY'}

DELETING ELEMENTS
pop() method

This method removes an item with the provided key and returns the value.

EXAMPLE

>>> dict1={'R': 'MONSOON', 'S': 'SUMMER', 'W': 'WINTER', 'A': 'AUTUMN', 'C': 'CLOUDY'}

>>> print(dict1.pop('R'))

OUTPUT

MONSOON

popitem() method

The method, popitem() can be used to remove and return an arbitrary item (key, value)
form the dictionary.

EXAMPLE
>>> print(dict1.popitem())

OUTPUT

('C', 'CLOUDY')

EXAMPLE

>>> print(dict1.popitem())

OUTPUT

('A', 'AUTUMN')

clear() method

All the items of a dictionary can be removed at once using the clear() method.

>>>dict1.clear()

DICTIONARY OPERATIONS

Len()

Return the length (the number of items) in the dictionary.

>>> dict1={'R':'RAINY' , 'S':'SUMMER', 'W':'WINTER' , 'A':'AUTUMN'}

>>> len(dict1)

>>> dict2={'num':10, 1:20, 1:30}


>>> len(dict2)

NOTE: The number of elements is counted as 2 because key 1 is repeated.

Membership

We can test if a key is in a dictionary or not using the keyword in.

>>> dict3={4:40, 5:50}

>>> print(4 in dict3)

>>> print(6 in dict3)

NOTE: The membership test is for keys only, not for values.

True

False

Iteration

Using a for loop we can iterate though each key in a dictionary.

dict1={'R':'RAINY' , 'S':'SUMMER', 'W':'WINTER' , 'A':'AUTUMN'}

for i in dict1:
print(dict1[i])

RAINY

SUMMER

WINTER

AUTUMN

sorted()

Return a sorted list of keys in the dictionary .

>>> print(sorted(dict1))

['A', 'R', 'S', 'W']

PYTHON DICTIONARY FUNCTIONS

item()

Return a view of the dictionary's items (key, value). The key and value pair will be in the
form of a tuple, which is not in any particular order.

>>> dict3={4:40, 5:50}

>>> dict3.items()

dict_items([(4, 40), (5, 50)])

keys()
It returns a list of the key values in a dictionary.

>>> dict3={4:40, 5:50}

>>> dict3.keys()

dict_keys([4, 5])

values()

It returns a list of values from key-value pairs in a dictionary.

>>> dict3={4:40, 5:50}

>>> dict3.values()

dict_values([40, 50])

get(key,d)

Return the value of key. If key does not exit, return d

>>> dict3={4:40, 5:50}

>>> dict3.get(4, 'NOT PRESENT')

40

>>> dict3.get(8, 'NOT PRESENT')

'NOT PRESENT'

update()

Update the dictionary with the key/value pairs from other dictionary, overwriting existing
keys.
It merges the keys and values of one dictionary into another and overwrites values of
the same key.

>>> dict2={1,10: 2,20:, 3:30}

>>> dict3={4:40, 5:50}

>>> dict2.update(dict3)

>>> print(dict2)

{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}

You might also like