fbpx

Dictionaries

A dictionary (also referred to as an associative array, or a hash table) in Python is another structure we can use to store a collection of values. However, rather than referencing these values using an index (or position) like we did with lists, we use a “key”, which is a custom identifier. We call these elements in a dictionary “key-value pairs”. Dictionaries can contain elements of different data types. 

We create a dictionary using curly braces { }, and separate each individual key and value using a colon. For example:

				
					person1 = {"name": "Maria", "age": 25, "city": "Miami"}
				
			

To access a value in a dictionary, we put the corresponding key in hard brackets [] (similar to how we use an index to access items in a list). For example:

				
					person1 = {"name": "Maria", "age": 25, "city": "Miami"}

print(person1["name"])
# "Maria"
print(person1["age"])
# 25
print(person1["city"])
# "Miami"
				
			

You can also use the key to add or update values using the assignment (=) operator:

				
					person1 = {"name": "Maria", "age": 25, "city": "Miami"}

# update a value:
person1["age"] = 26

# add a new key-value pair
person1["occupation"] = "Teacher"
				
			

Dictionaries are helpful to use when we need an additional way to refer to values in a data structure other than just by an index, and to manage the complexity of a program.

Replit Practice

Loading...