10 Dictionary
10 Dictionary
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++'}
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.
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.
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
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
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
Output
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
Dictionary comprehension
#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)
#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