Dictionary in Python
Dictionary in Python
Dictionary is listed in curly brackets, inside these curly brackets, keys and values
are declared. Each key is separated from its value by a colon (:) while each element
is separated by commas.
More than one entry per key is not allowed ( no duplicate key is allowed)
The values in the dictionary can be of any type while the keys must be immutable like
numbers, tuples or strings.
Dictionary keys are case sensitive- Same key name but with the different case are
treated as different keys in Python dictionaries.
Example
Create and print a dictionary:
CMPINFOTECH pg. 1
Python Programming Dictionary CMP Infotech
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Accessing Items
You can access the items of a dictionary by referring to its key name, inside
square brackets:
Example
Get the value of the "model" key:
x = thisdict["model"]
print(x)
There is also a method called get() that will give you the same result:
Example
Get the value of the "model" key:
x = thisdict.get("model")
Change Values
You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
thisdict["year"] = 2018
CMPINFOTECH pg. 2
Python Programming Dictionary CMP Infotech
When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.
Example
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Example
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
Example
You can also use the values() function to return values of a dictionary:
for x in thisdict.values():
print(x)
Example
Loop through both keys and values, by using the items() function:
for x, y in thisdict.items():
print(x, y)
CMPINFOTECH pg. 3
Python Programming Dictionary CMP Infotech
Example
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use
the len() method.
Example
Print the number of items in the dictionary:
print(len(thisdict))
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning
a value to it:
Example
thisdict["color"] = "red"
print(thisdict)
Removing Items
There are several methods to remove items from a dictionary:
CMPINFOTECH pg. 4
Python Programming Dictionary CMP Infotech
Example
The pop() method removes the item with the specified key name:
thisdict.pop("model")
print(thisdict)
Example
The popitem() method removes the last inserted item (in versions before 3.7, a
random item is removed instead):
thisdict.popitem()
print(thisdict)
Example
The del keyword removes the item with the specified key name:
del thisdict["model"]
print(thisdict)
Example
The del keyword can also delete the dictionary completely:
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer
exists.
Example
The clear() keyword empties the dictionary:
thisdict.clear()
print(thisdict)
CMPINFOTECH pg. 5
Python Programming Dictionary CMP Infotech
a Dictionary
You 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.
There are ways to make a copy, one way is to use the built-in Dictionary
method copy().
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
Example
Make a copy of a dictionary with the dict() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
CMPINFOTECH pg. 6
Python Programming Dictionary CMP Infotech
Example
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)
However, the values can be accessed in the dictionary by using the keys as keys are unique
in the dictionary.
Output:
<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE
Python provides us with an alternative to use the get() method to access the dictionary
values. It would give the same result as given by the indexing.
CMPINFOTECH pg. 7
Python Programming Dictionary CMP Infotech
Output:
<class 'dict'>
printing Employee data ....
{'Name': 'John', 'salary': 25000, 'Company': 'GOOGLE', 'Age': 29}
Enter the details of the new employee....
Name: David
Age: 19
Salary: 8900
Company:JTP
printing the new data
{'Name': 'David', 'salary': 8900, 'Company': 'JTP', 'Age': 19}
Output:
<class 'dict'>
printing Employee data ....
{'Age': 29, 'Company': 'GOOGLE', 'Name': 'John', 'salary': 25000}
CMPINFOTECH pg. 8
Python Programming Dictionary CMP Infotech
Iterating Dictionary
A dictionary can be iterated using the for loop as given below.
Example 1
# for loop to print all the keys of a dictionary
Output:
Name
Age
salary
Company
Example 2
#for loop to print all the values of the dictionary
Output:
CMPINFOTECH pg. 9
Python Programming Dictionary CMP Infotech
John
29
25000
GOOGLE
Example 3
#for loop to print the values of the dictionary by using values() method.
Output:
John
29
25000
GOOGLE
Example 4
#for loop to print the items of the dictionary by using items() method.
Output:
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
Summary:
CMPINFOTECH pg. 10
Python Programming Dictionary CMP Infotech
CMPINFOTECH pg. 11