0% found this document useful (0 votes)
3 views

Python Dictionary

Dictionaries in Python are collections that store data as key-value pairs, where each key must be unique. They are mutable, allowing for the addition, updating, and removal of elements, and can be accessed using keys. Various methods such as get(), items(), keys(), and pop() are available for manipulating and retrieving data from dictionaries.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Dictionary

Dictionaries in Python are collections that store data as key-value pairs, where each key must be unique. They are mutable, allowing for the addition, updating, and removal of elements, and can be accessed using keys. Various methods such as get(), items(), keys(), and pop() are available for manipulating and retrieving data from dictionaries.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Dictionary

Dictionaries are also collection/ containers and store data in form of key : value
pairs.
Dictionary contains many key : value pair, with each pair separated by comma
enclosed in curly brackets.

Characteristics of Dictionary –

• Dictionary is not sequential.


• It is indexed via its key.
• Each key in dictionary must be unique i.e. Dictionaries cannot have two items
with the same key
Syntax – Dictionary in python is declared as

d={
<key>: <value>,
<key>: <value>,
...
<key>: <value>
}

#empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}
Accessing Elements from Dictionary –

A dictionary uses keys to access data elements. Keys can be used either inside
square brackets [] or with the get() method.

Syntax –

Dictionary name[key]

If we use the square brackets [], KeyError is raised in case a key is not found in the
dictionary.

my_dict = { 1: 'apple', 2: 'ball’, 3: ‘cup’, 4’doll’ }


Print(my_dict[3])

my_dict = {'name': 'John', 1: [2, 4, 3]}


Print(my_dict[john])
Updating existing and Adding new Dictionary elements –

Dictionaries are mutable. We can add new items or change the value of existing
items using an assignment operator.

If the key is already present, then the existing value gets updated. In case the key
is not present, a new (key: value) pair is added to the dictionary.

teachers ={'math':'raj' , 'science': 'sunil' , 'gk':'rani'}


print(teachers)

teachers ['cs']='samir'
print(teachers)

teachers['math'] = 'rushi'
print(teachers)

>> {'math': 'raj', 'science': 'sunil', 'gk': 'rani'}


{'math': 'raj', 'science': 'sunil', 'gk': 'rani', 'cs': 'samir'}
{'math': 'rushi', 'science': 'sunil', 'gk': 'rani', 'cs': 'samir'}
Traversing through Dictionary elements –

Like other collections, dictionaries are also traversed using for loop.

teachers ={'math’ : 'raj' , 'science’ : 'sunil' , 'gk’ : 'rani’, ‘cs’: ‘samir’}

for item in teachers:


print(item)

>> math
science
gk
cs

Remember dictionaries are always accessed via its key. If you want to print the
values associated with each key use-

for item in teachers:


print(teachers[item])
Or
Print(item, ‘:’, teachers[item])  will print both key: value
Removing elements from Dictionary –

We can remove a particular item in a dictionary by using the del or pop command.

Del command

Syntax- del dictionary[key]

del teachers[‘math’]  removes key : value pair associated with key ‘math’

del teachers[‘civics’] prompts KeyError as key is not present in dictionary.

The popitem() method can be used to remove and return an arbitrary (key,
value) item pair from the dictionary. All the items can be removed at once, using
the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary
itself.
Check existence of elements in Dictionary –

We can use operators in and not in to check if key is present in dictionary.

Syntax-

Key in dictionary  Returns True if key is present otherwise false.

Key not in dictionary  Returns True if key is not present otherwise false.

teachers ={'math':'raj' , 'science': 'sunil' , 'gk':'rani'}

teachers ['cs']='samir'
teachers['math'] = 'rushi'

del teachers['math’]

print('math' in teachers)
print('civics'not in teachers)
Python Dictionary Methods

get() –This method return the value for the given key if present in the
dictionary. If not, then it will return None
Syntax : Dict.get(key, default=None)

items() method is used to return the list with all dictionary keys with values.
Syntax: dictionary.items()

keys() method list of all the keys in the dictionary in order of insertion in form of
list.
Syntax: dict.keys()

clear() method removes all items from the dictionary.


Syntax: dict.clear()

values() method returns a list of all the values available in a given dictionary.
Syntax: dictionary_name.values()
update() method updates the dictionary with the elements from another
dictionary object or from an iterable of key/value pairs.
Syntax: dict.update([other])

# Python program to show working


# of update() method in Dictionary

# Dictionary with three items


Dictionary1 = {'A’: Arun', 'B': ‘Benji', }
Dictionary2 = {‘C’: ‘Cloe’}
Dictionary3 = {‘B’: ‘BOB’}

Dictionary1.update(Dictionary2)
print("Dictionary after updation:")
print(Dictionary1)

Dictionary1.update(Dictionary3)
print("Dictionary after updation:")
print(Dictionary1)
pop() remove the key : value pair from dictionary and returns the value to user.

Syntax – dict.pop(key)

student = {"rahul":7, "Aditya":1, "Shubham":4}


suspended = student.pop("rahul")

# checking key of the element


print("suspended student roll no. = "suspended)

# printing list after performing pop()


print("remaining student =" student)
popitem() method removes the last inserted key-value pair from the dictionary
and returns it as tuple.
Syntax : dict.popitem()

test_dict = {"Nikhil": 7, "Akshat": 1, "Akash": 2}


# remove the last key value pair
res = test_dict.popitem()

print('The key, value pair returned is : ', res)

print("After using popitem(), test_dict: ", test_dict)

>> The key, value pair returned is : ('Akash', 2)


After using popitem(), test_dict: {'Nikhil': 7, 'Akshat': 1

You might also like