Professional Documents
Culture Documents
and methods
Dictionary
Dictionary is an unordered collection of items.
Each item of a dictionary has a key/value pair
creating a dictionary
Creating a dictionary is as simple as placing items
inside curly braces { } separated by commas
An item has a key and a corresponding value that is
expressed as a pair (key: value)
keys must be of immutable type
(string, number or tuple) and must be unique
values can be of any data type and can repeat
Dictionary
creating a dictionary:
# empty dictionary
my_dict = {}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# KeyError
print(my_dict['address'])
Changing and Adding 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
# Changing and adding Dictionary Elements
my_dict = {'name': 'Jack', 'age': 26}
# update value
my_dict['age'] = 27
print(my_dict) #Output: {'age': 27, 'name': 'Jack'}
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
Removing elements from Dictionary
We can delete an item from a dictionary using the
keyword del. It can even delete the dictionary
entirely
# Deleting items
my_dict = { ‘Rollno’ : 101, ‘Name’ : ‘Arav’ , ‘Course’: ‘B.Tech’}
# delete one item
del my_dict[‘Course’]
print(my_dict)
Example:
Students ={ ‘Ram’ : {‘DLD’:90, ‘PP’:98, ‘OOP’:89},
‘Krish’ : {‘DLD’:85, ‘PP’:84, ‘OOP’:81},
‘Lakshmi’ : {‘DLD’:100, ‘PP’:99, ‘OOP’:97}}
for key, val in Students.items():
print(key, val)
Dictionary Methods
clear() method removes all items from the
dictionary.
Example:
d = {1: "one", 2: "two"}
d.clear()
print('d =', d)
Output:
d = {}
Dictionary Methods
copy() method returns a shallow copy of the
dictionary.
Example:
original = {1:'one', 2:'two'}
new = original.copy()
print('Orignal: ', original)
print('New: ', new)
Output:
Orignal: {1: 'one', 2: 'two'}
New: {1: 'one', 2: 'two'}
Dictionary Methods
fromkeys(sequence[, value]) method creates a new
dictionary from the given sequence of elements with a
value provided by the user.
sequence - sequence of elements which is to be used as
keys for the new dictionary
value (Optional) - value which is set to each each
element of the dictionary
Example:
# vowels keys
keys = {'a', 'e', 'i', 'o', 'u' }
vals = ‘vowels’
vowels = dict.fromkeys(keys)
print(vowels)
Output: {'i': None, 'a': None, 'u': None, 'o': None, 'e': None}
Dictionary Methods
get(key[, value]) - returns the value for the specified
key if key is in dictionary
key - key to be searched in the dictionary
value (optional) - Value to be returned if the key is not
found. The default value is None
Example:
person = {'name': 'Phill', 'age': 22}
print('Name: ', person.get('name'))
print('Age: ', person.get('age'))
# value is not provided
print('Salary: ', person.get('salary'))
# value is provided
print('Salary: ', person.get('salary', 0.0))
Dictionary Methods
items() method returns a view object that displays
a dictionary of dictionary's (key, value) tuple pairs
Example:
# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.items())
Output:
dict_items([('apple', 2), ('orange', 3), ('grapes', 4)])
dictionary Methods
d = {'x': 2}
d.update(y = 3, z = 0)
print(d)
Output
{'x': 2, 'y': 3, 'z': 0}
Dictionary Methods
update([other]) method updates the dictionary with the elements from
the another dictionary object or from an iterable of key/value pairs
The update() method takes either a dictionary or an iterable object of
key/value pairs (generally tuples).
If update() is called without passing parameters, the dictionary remains
unchanged.
Example:
d = {1: "one", 2: "three"}
d1 = {2: "two"}
# updates the value of key 2
d.update(d1)
print(d)
d1 = {3: "three"}
# adds element with key 3 d.
update(d1) print(d)
Output:
{1: 'one', 2: 'two'}
{1: 'one', 2: 'two', 3: 'three‘}
Dictionary functions
Python has some built-in aggregate functions like:
Len(dict) – returns the length of the given
dictionray
my_dict = { ‘Rollno’ : 101, ‘Name’ : ‘Arav’ , ‘Course’:
‘B.Tech’}
print(len(my_dict)) #output: 3
all()Return True if all keys of the dictionary are
True (or if the dictionary is empty).
any() function returns True if any element of an
iterable is True. If not, any() returns False.
# 0 is False d = {0: 'False'}
print(any(d)) # 1 is True d = {0: 'False', 1: 'True'}
print(any(d))
Thank you