Python Dictionay
Python Dictionay
O Level / A Level
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
Each key is separated from its value by a colon (:)
Keys are unique within a dictionary while values may not be.
The values of a dictionary can be of any type, but the keys must be of an immutable data
type such as strings, numbers, or tuples.
Creating Dictionary
dict1 = {
"brand" : "Ford",
"model" : "Mustang",
"year" : 1964
}
dict2 = {‘Name’ : 'Zara', 'Age' : 7, 'Class' : 'First' }
dict3 = { } #Empty Dictionary
Access Items
We can access the items of dictionary by referring to its key name, inside square brackets.
get( ) method will be used to get the value of key.
Updating Dictionary
We can update a dictionary by adding a new entry or a key-value pair, modifying an existing
entry, or deleting an existing entry
dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict1['Age'] = 10
print ( dict1['Age'] )
Output
{'Name': 'Zara', 'Age': 10, 'Class': 'First'}
Output
{'Name': 'Zara', 'Age': 7, 'Class': 'First'}
{'Name': 'Zara', 'Age': 7, 'Class': 'First', 'Height': 4}
Zara
7
First
Zara
7
First
Name Zara
Age 7
Class First
Length of Dictionary
To determine how many items (key-value pairs) a Dictionary has, use the len( ) function.
e.g. print(len(dict1))
The del keyword removes the item with the specified key name.
dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict1.del('Name')
print(dict1)
The del keyword can also delete the dictionary completely.
dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict1
print(dict1)
Copy a Dictionary
We cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a
reference to dict1, and changes made in dict1 will automatically also be made in dict2.
To make a copy, one way is to use the built-in Dictionary method copy( ).
Another way to make a copy is to use the built-in method or constructor dict ( ).
dict3=dict(dict1)
print(dict2)
Nested Dictionaries
A dictionary can also contain many dictionaries, this is called nested dictionaries.
myfamily = {
"child1" : { "name" : "Emil", "year" : 2004 },
"child2" : { "name" : "Tobias", "year": 2007 },
"child3" : { "name" : "Linus", "year" : 2011 }
}
print(myfamily)
Output
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year':
2007}, 'child3': {'name': 'Linus', 'year': 2011}}
Assignment
1. Define Dictionary
2. Write the output from the following code:
A={1:100,2:200,3:300,4:400,5:500}
print (A.items() )
print (A.keys())
print (A.values())