In the last lesson, we covered lists and tuples, which are the two most fundamental ways of storing data in an organized manner. The only difference between both was that the lists are mutable, whereas tuples are immutable. Now, it’s time to explore a bit more advanced data structures, i.e., Dictionaries and Sets that allow you to retrieve data with labels and manage collections with unique values.
In this article, we will learn how to leverage dictionaries for efficient data retrieval and how sets help us manage distinct items easily.
Dictionaries: Key Value Pairs for Associative Arrays
A Dictionary is a collection of key-value pairs where the key represents the name assigned to each value in the collection. It is the practical implementation of a hash map or an associative array. To understand this, consider a real dictionary where a word represents the key and its meaning represents its value.
- The dictionaries in Python are ordered.
- Like lists, they are mutable, meaning that you can dynamically add, remove, or modify their elements.
- The keys in a dictionary must be unique and immutable. No two values can have similar keys.
- Although the keys have to have a single type, values can have any data type.
Declaring and Initializing Dictionaries
You can declare and initialize dictionaries the same as lists, except that they are enclosed in curly braces, and each item in a dictionary has to have a name (key).
Syntax:
dictionary_name = {key: value, key: value, key: value}
Example:
user = {"name": "John", "age": 40, "city": "London"}
You can also use the dict()
constructor to declare a dictionary.
Syntax:
dictionary_name = dict(key=value, key=value, key=value)
Example:
student = dict(name="John", id=123, major="SC")
Accessing Dictionary Elements
The best part about dictionaries is that you do not need to remember the index number of the elements in order to access them. You can simply use keys, which are much easier to remember.
Access Elements Bracket Syntax
Syntax:
dictionary_name[key]
Example:
user = {"name" : "John Smith", "age": 35, "designation" : "Admin"}
print("Name = ", user["name"])
print("Age: ", user["age"])
print("Role: ", user["designation"])
Output:
Name = John Smith
Age: 35
Role: Admin
Access Elements Using get() Method
The get()
method allows you to access the elements stored in a dictionary with the key. The only difference between this and the previous method is that you do not get an error if the key is not found using the get()
method.
Syntax:
dictionary_name.get(key)
Example:
user = {"name" : "John Smith", "age": 35, "designation" : "Admin"}
print("Name = ", user.get("name"))
print("Age: ", user.get("age"))
print("Role: ", user.get("designation"))
print("Address: ", user.get("address", "Not Defined!")) #Returns not defined
Output:
Name = John Smith
Age: 35
Role: Admin
Address: Not Defined!
Modifying Dictionary Elements
In Python, the dictionaries are mutable. Although you cannot change keys, you can change the values associated with them.
Adding a New Element
Syntax:
dictionary_name[new_key] = new_value
Example:
user = {"name" : "John Smith", "age": 35, "designation" : "Admin"}
user["address"] = "Main Street, NYC" # Adds a new pair to the dictionary
print(user) # Prints the entire dictionary
Output:
{'name': 'John Smith', 'age': 35, 'designation': 'Admin', 'address': 'Main Street, NYC'}
Updating an Existing Value
Syntax:
dictionary_name[key] = new_value
Example:
user = {"name" : "John Smith", "age": 35, "designation" : "Admin"}
user["name"] = "Alice" # Changes the name to Alice
print(user) # Prints the entire dictionary
Output:
{'name': 'Alice', 'age': 35, 'designation': 'Admin'}
Removing Elements from a Dictionary
You can easily remove elements from a dictionary using the built-in function.
Removing a Single Item
Syntax:
del dictionary_name[key]
Example:
user = {"name" : "John Smith", "age": 35, "designation" : "Admin"}
del user["age"] # Deletes age
print(user) # Prints the entire dictionary
Output:
{'name': 'John Smith', 'designation': 'Admin'}
Removing All Items
Syntax:
dictionary_name.clear()
Example:
user = {"name" : "John Smith", "age": 35, "designation" : "Admin"}
user.clear() # Removes everything from the dictionary
print(user) # Prints the entire dictionary
Output:
{}
Iterating Through Dictionaries
You can use the ‘for’ loop to iterate through dictionaries in various ways.
Iterating Through Keys
Syntax:
for key in dictionary_name:
statement(s)
Example:
user = {"name" : "John Smith", "age": 35, "designation" : "Admin"}
for key in user:
print(user[key]) #prints value associated with each key.
Output:
John Smith
35
Admin
Iterating Over Values
Syntax:
for value in dictionary_name.values():
statement(s)
Example:
user = {"name" : "John Smith", "age": 35, "designation" : "Admin"}
for value in user.values():
print(value) #prints values.
Output:
John Smith
35
Admin
Iterating Through Key-Value Pairs
Syntax:
for key, value in dictionary_name.items():
statement(s)
Example:
user = {"name" : "John Smith", "age": 35, "designation" : "Admin"}
for key, value in user.items():
print(key, " : ", value)
Output:
name : John Smith
age : 35
designation : Admin
Finding Length of a Dictionary
To find the number of items in a dictionary, you can use the len()
method:
Syntax:
len(dictionary_name)
Example:
user = {"name" : "John Smith", "age": 35, "designation" : "Admin"}
print(len(user)) # Returns 3
Output:
3
Sets: Unordered Collections of Unique Elements
A set is an unordered collection of distinct elements. It stores only one value even if a value is duplicated.
- Sets are unordered, meaning that they do not have to be arranged in a certain order.
- You can add or remove elements from a set after its declaration.
- The items must have the same data type.
Creating and Initializing Sets
You can create a set just like any other collection.
Syntax:
setname = {value1, value2, value3}
Example:
numbers = {1, 3, 3, 7, 2}
Adding Elements to a Set
You can use the add()
method to add elements to a set.
Syntax:
setname.add(element)
Example:
numbers = {1, 3, 3, 7, 2}
numbers.add(10)
print(numbers) # Prints the entire set
Output:
{1, 2, 3, 7, 10}
Removing Elements From a Set
With remove()
and clear()
methods, we can remove elements from a set.
remove()
Syntax:
setname.remove(element)
Example:
numbers = {1, 3, 3, 7, 2}
numbers.remove(3)
print(numbers) # Prints the entire set
Output:
{1, 2, 7}
clear()
Syntax:
setname.clear()
Example:
numbers = {1, 3, 3, 7, 2}
numbers.clear()
print(numbers) # Prints the entire set
Output:
set()
Besides the above, you can perform different operations on sets such as union (combining two sets), intersection (finding commons in two sets), difference (finding different elements in two sets), etc, but we will explore them in the future wherever the need arises. At this level, understanding sets and dictionaries to where we have learned is enough. You have successfully added another important tool to your programming skills. Keep it up!
Next up, we will learn about error handling in Python.