We have boarded the plane and embarked on our journey into the world of Python. Having explored the terrain of lists and tuples, it's now time for us to venture into the bustling cities of dictionaries. Please fasten your seatbelts, as we dive deeper into this fascinating landscape!
Suppose you're traveling and have to remember the capitals of numerous countries. You could remember each one individually, but wouldn't it be more efficient if you had a map where each country leads to its capital? That's what dictionaries in Python are like: they're comparable to compact maps where each key (such as country names) unlocks a value (like their capitals).
Dictionaries can be thought of as sets of key:value pairs. Any immutable type can be a key. A key is unique within a single dictionary.
In Python, an empty dictionary is represented by a pair of braces {}
. To create a dictionary with starting key:value pairs:
Python1# Creating a simple dictionary to hold the country as key and its capital as value 2capital_cities = { 3 "France": "Paris", 4 "Japan": "Kyoto", 5 "Kenya": "Nairobi", 6}
Unlike sequences, dictionaries
are indexed by their keys. So, in the above example, to get the capital city of France you would use "France"
as the key like so: capital_cities["France"]
.
Update existing values or store new ones by assigning the value to a key:
Python1# Add more capital cities 2capital_cities["Switzerland"] = "Bern" 3capital_cities["Germany"] = "Berlin" 4capital_cities["Japan"] = "Tokyo" # Update to new capital
Use the del
operator to delete a key:value pair from a dictionary
:
Python1del capital_cities["Germany"] # Removes "Germany" : "Berlin"
In this unit, we're going to guide you through creating, accessing, and manipulating elements within dictionaries
, ensuring you're equipped with the keys to unleash Python's potential.
In programming, it's crucial to organize and access data efficiently. Dictionaries are like efficient storage lockers for data where you can quickly find what you're looking for using a unique key. Unlike a list, where you might have to look through every item to find what you need, dictionaries let you go straight to the data—saving time and making your code faster. This makes dictionaries ideal for handling lots of data that you need to access and update often. Plus, dictionaries are versatile, so you can use them for many different tasks in programming, from storing user information to managing settings in an app. Learning about dictionaries is an essential step in becoming proficient in Python and handling data smartly.
Let's get started and uncover the secrets of dictionaries through practice with Cosmo on CodeSignal!