Dictionary in Python is a data structure. Dictionary is similar to HashTable with some extra features. HashTable is one of the most important data structures in computer science. You can use a dictionary as a HashTable.
HashTable is excellent in terms of time complexity and easy data access. We can access, add, update, and delete data in HashTable at a constant time. That means time complexity is O(1). But I am not going to discuss HashTable in-depth and its implementation. That is another broad topic. I put this information because this might help you.
In this blog, I am going to cover the dictionary and the uses of its methods.
Intro
In short, in a dictionary, items are stored as a key-value pair. Each of the keys is associated with a value. Basically, a dictionary is a collection of key-value pairs.
Here, we don’t need an index like an array/list to access data. We use a key that is associated with a value. A key can be a string, integer, boolean, or any other data type.
Create Python Dictionary
To create a dictionary, we need to use curly brackets. I think this is the easy and reasonable way rather than using the dict() function. And key-value are separated by a colon. Let’s see an example.
{'key': 'value'}
Not that you can write only one pair of key-value in a dictionary. You can write as many as you want. Each of the key-value has to be separated by a comma.
# Both are correct ways to write a dictionary. {'name': 'USA', 'Capital': 'Washington, D.C.', 'states': 50, 'currency': 'USD'} { 'name': 'USA', 'capital': 'Washington, D.C.', 'states': 50, 'currency': 'USD' } # We can store it in a variable like the below. country = { 'name': 'USA', 'capital': 'Washington, D.C.', 'states': 50, 'currency': 'USD' } print(country) # {'name': 'USA', 'capital': 'Washington, D.C.', 'states': 50, 'currency': 'USD'}
Let’s see some frequently used operations of dictionaries.
Read/Access
Reading or accessing data from a dictionary is pretty simple. We all know how to access a specific index element from an array. Similarly, we can access data in a dictionary. Instead of an index number, we need to write the key name inside the third bracket. The get() method also gives you the same result.
country = { 'name': 'USA', 'capital': 'Washington, D.C.', 'states': 50, 'currency': 'USD' } print(country['name']) # USA print(country['states']) # 50 # Access data using get() method print(country.get('capital')) # Washington, D.C.
Suppose you are looking for a key’s value that is not in the dictionary. Then you will get an error. To avoid it, you can use the get() method. The first parameter is the key (As you saw above), and the second parameter is the value you want to get if the key does not exist in the dictionary.
country['area'] # KeyError: 'area' val = country.get('area', 'Value') print(val) # Value
If you need to know all the keys in a dictionary, you can use the keys() method. It will return a list of all the keys. Similarly, to get all the values only, we can use values(). These list values are not accessible using the index. But these are iterable. Let’s see the example.
keys = country.keys() values = country.values() print(keys) # dict_keys(['name', 'capital', 'states', 'currency']) print(values) # dict_values(['USA', 'Washington, D.C.', 50, 'USD']) for val in keys: print(val) # name # capital # states # currency
Add and Update
Adding data in a dictionary is pretty straightforward. dictionary_name[key] = value. Let’s see.
country = { 'name': 'USA', 'capital': 'Washington, D.C.', 'states': 50, 'currency': 'USD' } country['area'] = '9.834 million km²' print(country) # {'name': 'USA', 'capital': 'Washington, D.C.', 'states': 50, 'currency': 'USD', 'area': '9.834 million km²'}
In a dictionary, keys are unique. You can’t store duplicate keys. If you try to add new data using an existing key, the previous one will replace with the current value. And this is how we can update data in a dictionary. Let’s try to update the name.
country['name'] = 'United States' print(country) # {'name': 'United States', 'capital': 'Washington, D.C.', 'states': 50, 'currency': 'USD', 'area': '9.834 million km²'}
You can also use the update() method. But I think the previous way is a good one.
Delete
There are several ways to delete an item from a dictionary.
If you want to delete a specific item, you can use the pop() method. This method takes a parameter, the item’s key, that we want to delete.
country = { 'name': 'United States', 'capital': 'Washington, D.C.', 'states': 50, 'currency': 'USD', 'area': '9.834 million km²' } print(country) # {'name': 'United States', 'capital': 'Washington, D.C.', 'states': 50, 'currency': 'USD', 'area': '9.834 million km²'} country.pop('area') print(country) # {'name': 'United States', 'capital': 'Washington, D.C.', 'states': 50, 'currency': 'USD'}
There is another method, which is popitem(). It is similar to the previous one. But it does not take any parameters. Instead, it removes lastly added items from the dictionary.
country = { 'name': 'United States', 'capital': 'Washington, D.C.', 'states': 50, 'currency': 'USD', 'area': '9.834 million km²' } country.popitem() print(country) # {'name': 'United States', 'capital': 'Washington, D.C.', 'states': 50, 'currency': 'USD'}
There is another method that might be helpful to you. If you need to delete all items at once from a dictionary, you can use clear().
country = { 'name': 'United States', 'capital': 'Washington, D.C.', 'states': 50, 'currency': 'USD', 'area': '9.834 million km²' } country.clear() print(country) # {}
In a dictionary, not that you can only store primitive type data. You can also keep a list, dictionary inside a dictionary, etc.
example = { 'list': [1, 2, 3, 4, 5], 'data': { 'text': 'Hello World' } } print(example)
Final Words
This blog is an overview of the python dictionary. I hope you found something helpful. But this is not the end. Try to create new dictionaries and apply these methods and practice more. Try to learn the use cases of a dictionary. Most importantly, try to go beyond this blog content.