[go: up one dir, main page]

0% found this document useful (0 votes)
39 views29 pages

10 Dictionary

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

10 Dictionary

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

Handling Dictionary in Python

Dictionary
 Python dictionary is an unordered collection of items.
 Each item of a dictionary has a key/value pair.
 The keys pair with values using a colon (:) while the commas
work as a separator for the elements.
 The entire dictionary object uses curly braces ({}) to enclose
itself.
Output
# empty dictionary
dict1 = {} {}
print(dict1) {1: 'C', 2: 'C++'}

# dictionary with integer keys


dict2 = {1: 'C', 2: 'C++'}
print(dict2)
maths=[]
Dictionary
for i in range(3):
maths.append(input("Enter marks for the 1st Subjects"))
print(maths)
sci=[]
for i in range(3):
sci.append(input("Enter marks for the 3rd Subjects"))
print(sci)
marks={"Mathemetics":maths,"Science":sci}
print(marks)
Dictionary
 The value in a dictionary can be of any valid Python data type.
But the keys have a constraint to be of any immutable data
types such as a string, a number, or a tuple.
 Keys inside a dictionary can’t have duplicates, but their values
can repeat themselves.
Example:
# string as a key
dict3 = {'Name': 'Mitesh', 'Roll': 12, 'Sub': 'Java'}
print(dict3)
# Creating a Dictionary with Mixed keys
dict5 = {'Name': ‘Prince', 1: [10, 20, 30, 40]}
print("Dictionary with the use of Mixed Keys: ",dict5)
Output
{'Name': 'Mitesh', 'Roll': 12, 'Sub': 'Java’}
Dictionary with the use of Mixed Keys: {'Name': ‘Prince', 1: [10, 20, 30, 40]}
Dictionary
#Creating a Dictionary with each item as a Pair
dict4 = dict([(1, 'Geeks'), (2, 'For')])
print("Dictionary with each item as a pair: ",dict4)

# Creating a Nested Dictionary


Dict = {1: 'Dear', 2: 'Coders',
3:{'A' : 'Welcome', 'B' : 'to', 'C' : 'Python'}}
print(Dict)
Output
Dictionary with each item as a pair: {1: 'Geeks', 2: 'For’}
{1: 'Dear', 2: 'Programmers', 3: {'A': 'Welcome', 'B': 'to', 'C': 'Python'}}
Dictionary
Nested Dictionary
Accessing Dictionary Elements
 To access the items of a dictionary refer to its key name inside square
bracket [ ].

dict3 = {'Name': 'Mitesh', 'Roll': 12, 'Sub': 'Java'}


print("Name: ", dict3['Name'])
print("Roll No.': ", dict3['Roll'])
print("Subject: ", dict3['Sub'])

Output
Name: Mitesh
Roll No.': 12
Subject: Java
Adding Elements to Dictionary
 While adding a value, if the key value already exists, the value
gets updated otherwise a new Key with the value is added to
the Dictionary.
# Creating an empty Dictionary
Dict = {}
# Adding elements one at a time
Dict[0] = 'Folks'
Dict[2] = 'For'
Dict[3] = 1
print("Dictionary after adding 3 elements: ",Dict)
# Adding set of values to a single Key
Dict['Value_set'] = 2, 3, 4
print("After adding set of values: ",Dict)
# Updating existing Key's Value
Dict[2] = 'Welcome'
print("Updated key value: ",Dict)
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested' :{'1' : 'Male', '2' : 'Female'}}
print("Adding a Nested Key:",Dict)
Adding Elements to Dictionary

Output
Dictionary after adding 3 elements: {0: 'Folks', 2: 'For', 3: 1}
After adding set of values: {0: 'Folks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value: {0: 'Folks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key: {0: 'Folks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Male',
'2': 'Female'}}}
Accessing Elements of nested
dictionary
 In this case, we have to use main key at first and then sub key.

# Creating a Dictionary
Dict = {'d1': {1: 'Programmers'},
'd2': {'language': 'Python'}}
# Accessing element using key
print(Dict['d1'])
print(Dict['d1'][1])
print(Dict['d2'][‘language'])

Output
{1: 'Programmers'}
Programmers
Python
Dictionary Methods
get() Used to access a value for a given key.

pop() Returns and deletes the value of the key specified.

popitem() Returns and removes the last key-value pair from dictionary. (Python version 3.6 onwards)
Before version 3.6, it returns arbitrary(random) key-value pair.
clear() Removes all items from the dictionary.

keys() Returns list of dictionary keys


Values() Returns list of dictionary values
items() Returns list of (key, val) tuple pairs
has_key() Returns true if key is existing inside dictionary dictionary otherwise false (removed from
Python3)
copy() Returns a shallow copy of the dictionary.

update() Updates one dictionary with another dictionary by merge operation


setdefault() Returns the value of a key (if the key is in dictionary). If not, it inserts key with a value to the
dictionary.
get() method
 In conventional method of retrieving value from the dictionary raises error if
key is not present.
dic = {"A":1, "B":2} Traceback (most recent call last):
print(dic["A"]) File ".\dic.py", line 3, in
print(dic["C"]) print (dic["C"])
KeyError: 'C'
 The get() method is used to avoid such situations. This
method returns the value for the given key if present in
the dictionary. If not, then it will return None (if get() is
used with only one argument).
dic = {"A":1, "B":2}
print(dic.get("A")) 1
print(dic.get("C")) None
print(dic.get("C","Not Found ! ")) Not Found !
Removing elements from dictionary using pop()
and popitem()
 Pop() requires key as an argument to delete the key-val pair

Dict = {2: 'Coders', 'name': 'for', 5: 'Python'} After deletion: {'name': 'for', 5: 'Python'}
# Deleting a key using pop() method Value of poped key is: Coders
pop_ele = Dict.pop(2)
print('After deletion: ',Dict)
print('Value of poped key is: ',pop_ele)
 The popitem() method is used to delete the last key-val
pair.
Dict = {2: 'Coders', 'name': 'for', 5: 'Python'}
After deletion: {2: 'Coders', 'name': 'for'}
pop_ele=Dict.popitem();
Value of poped key is: (5, 'Python')
print('After deletion: ',Dict)
print('Value of poped key is: ',pop_ele)

○ Note: In Python versions less than 3.6, popitem() would return an arbitrary
(random) key-value pair since Python dictionaries were unordered before version
3.6.
Removing elements from dictionary using del

 Deletion of keys can be done by using the del keyword.


 Using del keyword, specific values from a dictionary as well as whole
dictionary can be deleted.
# Initial Dictionary
Dict = { 5 : 'Come', 6 : 'on', 7 : 'Programmers',
'a' : {3 : 'Code', 5 : 'For', 7 : 'Python'},
'b' : {2 : 'Enjoy', 4 : 'coding'}}
print("Initial Dictionary: ")
print(Dict)
# Deleting a Key value
del Dict[7]
print("Deleting a specific key: ",Dict)
# Deleting a Key from Nested Dictionary
del Dict['a'][5]
print("Deleting a key from Nested Dictionary: ",Dict)
Removing elements from dictionary using del

Output

Initial Dictionary:
{5: 'Come', 6: 'on', 7: 'Programmers', 'a': {3: 'Code', 5: 'For', 7: 'Python'}, 'b': {2: 'Enjoy', 4: 'coding'}}
Deleting a specific key: {5: 'Come', 6: 'on', 'a': {3: 'Code', 5: 'For', 7: 'Python'}, 'b': {2: 'Enjoy', 4: 'coding'}}
Deleting a key from Nested Dictionary: {5: 'Come', 6: 'on', 'a': {3: 'Code', 7: 'Python'}, 'b': {2: 'Enjoy', 4:
'coding'}}
○ Note: “
 #del Dict_var will delete entire dictionary.
○ #clear() method clears all keys from the dictionary.
len(), keys(), values(),items()

langd={1:'C',2:'C++',3:'Java',4:'Python'}
print(len(langd))
print(langd.keys())
print(langd.values())
print(langd.items())

Output
4
dict_keys([1, 2, 3, 4])
dict_values(['C', 'C++', 'Java', 'Python'])
dict_items([(1, 'C'), (2, 'C++'), (3, 'Java'), (4, 'Python')])
has_key()

 has_key() method returns true if specified key is present in the dictionary, else
returns false. [removed from Python3]
 We can use __contains__() method or in operator

langd={1:'C',2:'C++',3:'Java',4:'Python'}
print(langd.__contains__(3))
print(langd.__contains__(5))
print(4 in langd)

Output
True
False
True
○ Note: “
 Copy() method is same as list. (shallow copy).To get deep copy, simply assign one
dictionary to another one.
update()
 Updates the dictionary with the elements from the another dictionary object or
from an iterable of key/value pairs.
 If key doesn’t exist in the first dictionary then it would be added with value and if key
is already present then the value is replaced with the second dictionary.

lang1={1:'C',2:'C++',3:'Java',4:'Python'}
lang2={5:'VB',6:'FORTRAN'}
lang1.update(lang2)
print(lang1)
lang3={1:'PHP',7:'Perl'}
lang1.update(lang3)
print(lang1)

Output
{1: 'C', 2: 'C++', 3: 'Java', 4: 'Python', 5: 'VB', 6: 'FORTRAN'}
{1: 'PHP', 2: 'C++', 3: 'Java', 4: 'Python', 5: 'VB', 6: 'FORTRAN', 7: 'Perl'}
setdefault()
 Returns the value of a key (if the key is in dictionary). If not, it inserts key with a
value to the dictionary.

lang1={1:'C',2:'C++',3:'Java',4:'Python'}
print(lang1.setdefault(10))
print(lang1)
print(lang1.setdefault(11,'PHP'))
print(lang1)

Output

{1: 'C', 2: 'C++', 3: 'Java', 4: 'Python', 10: None}


{1: 'C', 2: 'C++', 3: 'Java', 4: 'Python', 10: None, 11: 'PHP'}
Iterating through dictionary
lang1={1:'C',2:'C++',3:'Java',4:'Python'}
for key in lang1.keys():
print(key)
for key, value in lang1.items():
print(key, '->', value)
#some calculation
prices = {'pen': 0.28, 'pencil': 0.24, 'eraser': 0.15}
for k, v in prices.items():
prices[k] = round(v * 0.09, 2) # Apply a 9% discount
print(prices)

# Generating a new dictionary


a_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
new_dict = {} # Create a new empty dictionary
for key, value in a_dict.items():
if value <= 2:
new_dict[key] = value
print(new_dict)
Iterating through dictionary

Output

1
2
3
4
1 -> C
2 -> C++
3 -> Java
4 -> Python
{'pen': 0.25, 'pencil': 0.22, 'eraser': 0.14}
{'one': 1, 'two': 2}
Iterating through dictionary

#key as value and value as key


b_dict={}
a_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
for key,value in a_dict.items():
b_dict[value]=key
print(b_dict)

Output
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
Dictionary comprehension

 Dictionary comprehension is a method for transforming one dictionary into another


dictionary.
 During this transformation, items within the original dictionary can be conditionally
included in the new dictionary and each item can be transformed as needed.

#With Loop
dict2={}
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} Output
for k,v in dict1.items(): {'a': 2, 'b': 4, 'c': 6, 'd': 8, 'e': 10}
dict2[k]=v*2 {'a': 2, 'b': 4, 'c': 6, 'd': 8, 'e': 10}
print(dict2)

#With comprehension
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# Double each value in the dictionary
double_dict1 = {k:v*2 for (k,v) in dict1.items()}
print(double_dict1)
Dictionary comprehension with if
#Comprehension with if Output
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} {'c': 3, 'd': 4, 'e': 5}
# Check for items greater than 2
dict1_cond = {k:v for (k,v) in dict1.items() if v>2}
print(dict1_cond)

#Comprehension with double if


dict1_doubleCond = {k:v for (k,v) in dict1.items() if v>2 if v%2 == 0}
print(dict1_doubleCond) {'d': 4}

#Comprehension with triple if


dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f':6}
dict1_tripleCond = {k:v for (k,v) in dict1.items() if v>2 if v%2 == 0 if v%3 == 0}
print(dict1_tripleCond)
{'f': 6}
Dictionary comprehension with if…else

#with if..else
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f':6}
# Identify odd and even entries
dict1_evenodd = {k:('even' if v%2==0 else 'odd') for (k,v) in dict1.items()}
print(dict1_evenodd)

Output
{'a': 'odd', 'b': 'even', 'c': 'odd', 'd': 'even', 'e': 'odd', 'f': 'even'}
THANKS!
Any questions?
You can find me at
▸ avanishvishwakarma96@gmail.com

You might also like