Python Dictionary
What is Dictionary?
How to create Dictionary?
# Empty Dictionary
my_dict = {}
print("Empty dictionary is created",my_dict)
# Dictionary with Integer keys
colors = {1:'red', 2:'green', 3:'Yellow'}
print("Dictionary with integer keys are created ",colors)
# Dictionary with mixed keys
my_dict = {'name': 'vinoth', 1: ['red', 'green']}
print("Dictionary with mixed keys are created",my_dict)
# Checking the Type
print(type(my_dict))
Output:
Empty dictionary is created {}
Dictionary with integer keys are created {1: 'red', 2: 'green', 3: 'Yellow'}
Dictionary with mixed keys are created {'name': 'vinoth', 1: ['red', 'green']}
<class 'dict'>
Note - No duplicate keys are allowed
# Dictionary with duplicate keys
colors = {1:'red', 2:'green', 3:'Yellow', 2:'blue'} # key 2 mentioned twice
print("Key 2 is updated with last assigned value",colors)
Output:
Key 2 is updated with last assigned value {1: 'red', 2: 'blue', 3: 'Yellow'}
How to access elements from a dictionary?
# Access the key which is available in the dictionary
mydetails = {'name': 'Vinoth','age':30, 'address': 'Chennai'}
print(mydetails['name'])
print(mydetails['address'])
Output:
Vinoth
Chennai
# Access the key which is not available in the dictionary - KeyError will be displayed
print(mydetails['phonenumber'])
Output:
KeyError: Traceback (most recent call last)
<ipython-input-28-355917c6fc04> in <module>()
1 # Access the key which is not available in the dictionary
----> 2 print(mydetails['phonenumber'])
KeyError: 'phonenumber'
How to access the element using Get Method?
#Create a dictionary
mydetails = {'name': 'Vinoth','age':30, 'address': 'Chennai'}
# Access the key which is available in the dictionary
print(mydetails.get('name'))
# Access the key which is not available in the dictionary
print(mydetails.get('phonenumber'))
Output:
Vinoth
None
How to add elements(key) in a dictionary?
#Create a dictionary
mydetails = {'name': 'Vinoth','age':30, 'address': 'Chennai'}
# Add phonenumber
mydetails['phonenumber'] = '+91-6383544892'
print(mydetails)
Output:
{'name': 'Vinoth', 'age': 30, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
How to change/update existing element(value) in a dictionary?
# Updating the value
mydetails['age'] = 31
print(mydetails)
Output:
{'name': 'Vinoth', 'age': 31, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
How to delete an elements in a dictionary?
1. pop() Method
pop() Method - Remove the item from the dictionary, if the key is not found KeyError will be thrown. It will also returns the removed value
#Create a dictionary
mydetails = {'name': 'Vinoth', 'age': 31, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
#Remove a particular item
print(mydetails.pop('phonenumber'))
print(mydetails)
Output:
+91-6383544892
{'name': 'Vinoth', 'age': 31, 'address': 'Chennai'}
2. popitem() Method
popitem() Method - To remove and return an arbitrary item (key, value)
#Create a dictionary
mydetails = {'name': 'Vinoth', 'age': 31, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
# It remove the last item in the dictionary
mydetails.popitem()
print(mydetails)
Output:
{'name': 'Vinoth', 'age': 31, 'address': 'Chennai'}
3. del Keyword
del keyword to remove individual item or the entire dictionary itself.
#Sample code to delete a particular item
# Dictionary with cubes of number
cube = {1:1, 2:8, 3:27, 4:64, 5:125}
# Delete particular key
del cube[4]
print(cube)
Output:
{1: 1, 2: 8, 3: 27, 5: 125}
#Sample code to delete the entire dictionary
# Dictionary with cubes of number
cube = {1:1, 2:8, 3:27, 4:64, 5:125}
# Delete the entire dictionary
del cube
# NameError is displayed as the entire dictionary is deleted
print(cube)
Output:
NameError: Traceback (most recent call last)
<ipython-input-50-7e054bd83a54> in <module>()
8
9 # NameError is displayed as the entire dictionary is deleted
---> 10 print(cube)
NameError: name 'cube' is not defined
4. clear() Method
Clear Method - All the items can be removed at once, without deleting the dictionary
# Dictionary with cubes of number
cube = {1:1, 2:8, 3:27, 4:64, 5:125}
#Remove all items
cube.clear()
print("Empty dictionary is displayed",cube)
Output:
Empty dictionary is displayed {}
Looping items in the dictionary
# Dictionary with cubes of number
cube = {1:1, 2:8, 3:27, 4:64, 5:125}
for num in cube:
print("Cube of",num,"is",cube[num])
Output:
Cube of 1 is 1
Cube of 2 is 8
Cube of 3 is 27
Cube of 4 is 64
Cube of 5 is 125
Dictionary Methods
1. length - len()
Length of dictionary, i.e. the number of elements in the dictionary.
#Create a dictionary
mydetails = {'name': 'Vinoth', 'age': 31, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
print("length of the Dictionary is",len(mydetails))
Output:
length of the list is 4
2. Membership - ' in and not in' Operator
#Create a dictionary
mydetails = {'name': 'Vinoth', 'age': 31, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
# Sample Code for 'in' operator - True if key is in dictionary.
print('name' in mydetails)
# Sample Code for 'not in' operator -True if key is not in dictionary.
print('email' not in mydetails)
Output:
True
True
3. sorted()
# Sort the vowels in Ascending order
vowels = {'e': 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5}
print('Sorted Dictionary:', sorted(vowels))
Output:
Sorted Dictionary: ['a', 'e', 'i', 'o', 'u']
# Setting reverse=True sorts the dictionary in the descending order
vowels = {'e': 1, 'a': 2, 'u': 3, 'o': 4, 'i': 5}
print('Sorted Dictionary (in Descending):', sorted(vowels,reverse=True))
Output:
Sorted Dictionary (in Descending): ['u', 'o', 'i', 'e', 'a']
4. keys()
#Create a dictionary
mydetails = {'name': 'Vinoth', 'age': 31, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
print(mydetails.keys())
Output:
dict_keys(['name', 'age', 'address', 'phonenumber'])
5. values()
#Create a dictionary
mydetails = {'name': 'Vinoth', 'age': 31, 'address': 'Chennai', 'phonenumber': '+91-6383544892'}
print(mydetails.values())
Output:
dict_values(['Vinoth', 31, 'Chennai', '+91-6383544892'])
6. items()
# Dictionary with cubes of number
cube = {1:1, 2:8, 3:27, 4:64, 5:125}
print(cube.items())
Output:
dict_items([(1, 1), (2, 8), (3, 27), (4, 64), (5, 125)])
7. copy()
# Dictionary with cubes of number
cube = {1:1, 2:8, 3:27, 4:64, 5:125}
dictcopy = cube.copy()
print('Original:', cube)
print('New:', dictcopy)
Output:
Original: {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
New: {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
8. update()
Inserting the new value
# Dictionary with car details
car = {"brand": "Audi", "model": "A7", "year": 2019}
car.update({"color": "White"})
print(car)
Output:
{'brand': 'Audi', 'model': 'A7', 'year': 2019, 'color': 'White'}
Updating the existing value
# Dictionary with car details
car = {"brand": "Audi", "model": "A7", "color":"Blue" , "year": 2019}
car.update({"color": "White"})
print(car)
Output:
{'brand': 'Audi', 'model': 'A7', 'color': 'White', 'year': 2019}
Update with an iterable.
# Dictionary with car details
car = {"brand": "Audi", "model": "A7", "year": 2019}
# Updating with multiple key and values
car.update(cost = '68000$', color = 'White')
print("Dictionary after updation:",car)
Output:
Dictionary after updation:
{'brand': 'Audi', 'model': 'A7', 'year': 2019, 'cost': '68000$', 'color': 'White'}
9. fromkeys()
The fromkeys() method creates a new dictionary from the given sequence of elements with a value provided by the user.
The fromkeys() method takes two parameters:
# Creating a dictionary from a sequence of keys with value
# vowels keys
mykeys = {'a', 'e', 'i', 'o', 'u' }
value = 'vowels'
vowels = dict.fromkeys(mykeys, value)
print(vowels)
Output:
{'o': 'vowels', 'a': 'vowels', 'e': 'vowels', 'i': 'vowels', 'u': 'vowels'}
10. setdefault()
The setdefault() method returns the value of a key (if the key is in dictionary). If not, it inserts key with a value to the dictionary.
if key is not in the dictionary.
# Sample code
employee = {'name': 'Muthu'}
salary = employee.setdefault('salary')
print("Employee details :",employee)
print('salary=',salary)
Output:
Employee details : {'name': 'Muthu', 'salary': None}
salary= None
if key is not in the dictionary and default_value is provided
# Sample code
employee = {'name': 'Muthu'}
company = employee.setdefault('company', 'CTS')
print("Employee details :",employee)
print('company=',company)
Output:
Employee details : {'name': 'Muthu', 'company': 'CTS'}
company= CTS
11. dir()
Get list of all available methods and attributes of dictionary
mydict = {}
print(dir(mydict))
Output:
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__',
'__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys',
'pop', 'popitem', 'setdefault', 'update', 'values']
Dictionary Comprehension
#Using Dictionary comprehension
cubes = {x: x**3 for x in range(10)}
print(cubes)
Output:
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729}
Q. we have a list of fruits and we can use dict comprehension to create a dictionary with fruits, the list elements as the keys and the length of each string as the values
# create list of fruits
fruits = ['apple', 'mango', 'banana']
# dict comprehension to create dict with fruit name as keys
{f:len(f) for f in fruits}
Output:
{'apple': 5, 'mango': 5, 'banana': 6}