Python Dictionaries: 7 Insights to Master Dictionaries

Python dictionaries are a versatile and widely used data structure, especially when working with complex scenarios.

They store data in key-value pairs, allowing you to quickly retrieve values using their corresponding keys. Dictionaries are incredibly useful for tasks like managing metadata, building datasets, and much more.

Having practical knowledge of Python dictionary could help you a lot in many different scenarios, also it is asked a lot in interviews.

python dictionaries

In this blog, I am going to start from briefly talking about basics, and mostly going through practical problems related to dictionary.

If you’re new to Python dictionaries or looking to deepen your understanding, this blog will guide you through the basics and explore practical problems to enhance your skills. Let’s dive in!

Python Dictionary Basics

Let’s first start with the basic structure of Python dictionaries.

In python, you have to use {} to define the dictionary and you can use integers/strings as your key, but while using string make sure to use quotes (“/’) (JS users, this is for you to remember!).

my_blog = {
    "name": "thestartupcoder.com", 
    "author": "Arup", 
    "content": "Welcome to the blog!", 
    "created_at": "14/12/2024"
}

As you can see in this example, I am defining my_blog in this example.

This is the structure of dictionary and also this is one of the best examples where dictionaries could be used to represent the data.

One simple way to define dictionary is by just writing it. But that is not possible all the time.

Creating Dictionaries from Lists

There is another way of creating dictionaries from 2 lists, let’s talk about that now.

Sometimes, you might get some values as a list, and you have to create dictionary from them.

Let’s look at the following example where we create dictionary after `zip`ping the lists –

payment_terms = ["NET10", "NET20", "NET30"]
payment_values = [10, 20, 30]

payment_dict = dict(zip(payment_terms, payment_values))
print(payment_dict)

Output:
{'NET10': 10, 'NET20': 20, 'NET30': 30}

This method pairs corresponding elements from two lists into key-value pairs.

Next, let’s talk about the different ways of accessing the Python dictionary.

Accessing Python Dictionary Elements

In different scenarios, you might want to access the values of the dictionary you have created.

Accessing Values by Keys

Sometimes you want to get access to one of the values through the keys. Let’s say, in this example I want to get the name and author of my_blog. Then I will write something like this –

print(my_blog["name"]) # thestartupcoder.com

print(my_blog["author"]) # Arup

print(my_blog['likes']) # KeyError: 'likes'

But if the key does not exists then you will get KeyError, for that you can instead use get to not break your system –

print(my_blog.get('likes', 0)) # 0

Accessing Keys and Values

If you want to access the keys and values from the Python dictionary, then you have to use keys or values to get the keys or values respectively like this –

print(my_blog.keys())
# dict_keys(['name', 'author', 'content', 'created_at'])

print(my_blog.values())
# dict_values(['thestartupcoder.com', 'Arup', 'Welcome to the blog!', '14/12/2024'])

In case, you want to get the key-value pairs all at once then you can do something like this –

print(my_blog.items())
# dict_items([('name', 'thestartupcoder.com'), ('author', 'Arup'), ('content', 'Welcome to the blog!'), ('created_at', '14/12/2024')])

Python dictionary has items which gives you an iterator containing the items as tuple values. The tuple has key first and then value.

You can print dictionary keys and values through a for-loop in Python like this –

for key, value in my_blog.items():
    print(f"{key}: {value}")
    
Output:
name: thestartupcoder.com
author: Arup
content: Welcome to the blog!
created_at: 14/12/2024

Counting Items in a Dictionary

In Python, just like list, you can use len to count the values in dictionary –

print(len(my_blog)) # 4

Updating Python Dictionaries

Another necessary stuff that you will do a lot is – inserting values and updating values in Python dictionary.

Inserting and updating are pretty simple with dictionary, you just have to call update method with new key-value pairs and it will automatically add them if the key is new otherwise update the already existing key value.

my_blog = {
    "name": "thestartupcoder.com", 
    "author": "Arup", 
    "content": "Welcome to the blog!", 
    "created_at": "14/12/2024"
}

my_blog.update({"likes": 12})
print(my_blog)
# {'name': 'thestartupcoder.com', 'author': 'Arup', 'content': 'Welcome to the blog', 'created_at': '14/12/2024'}

my_blog.update({"author": "Arup Jana"})
print(my_blog)
# {'name': 'thestartupcoder.com', 'author': 'Arup Jana', 'content': 'Welcome to the blog', 'created_at': '14/12/2024'}

Remember update method changes the dictionary. In the first example, new key (content) is added, and in the second example already existing key (author) is updated.

Now that we have seen some basic stuff in Python dictionary, we can jump to some more practical stuff in dictionary that you might have to do.

Let’s start with how you would merge 2 dictionaries!

Merge Two Dictionaries

Merging two dictionaries in Python is as simple as writing a one-line code –

blog = {
    "title": "Python Dictionary", 
    "author": "Arup",
}

system_data = {
    "created_at": "14/12/2024", 
    "created_by": "arup@thestartupcoder.com"
}

blog_information = {**blog, **system_data}
print(blog_information)
# {'title': 'Python Dictionary', 'author': 'Arup', 'created_at': '14/12/2024', 'created_by': 'arup@thestartupcoder.com'}

print(blog | system_data)
# {'title': 'Python Dictionary', 'author': 'Arup', 'created_at': '14/12/2024', 'created_by': 'arup@thestartupcoder.com'}

You can use any of the given syntax for merging 2 dictionaries in Python. But, if you are using Python 3.5 or less then both of them will not work.

If that is the case, you have to use the following syntax –

print(dict(list(blog.items())+list(system_data.items())))
# {'title': 'Python Dictionary', 'author': 'Arup', 'created_at': '14/12/2024', 'created_by': 'arup@thestartupcoder.com'}

Next, if you want to remove any key from the dictionary how would you do it?

Remove Key from Dictionary

We can just use del key to delete any object after this like the following –

del blog['title']

But there is a chance of getting `KeyError` if the key does not exist. In that case, you can use `pop` with a default value to bypass the case if the key does not exist.

print(blog.pop("likes", 0))
# 0

You can also use this method when you want to get an item from dictionary, and at the same time delete it.

Sort Python Dictionary by Value

Sometimes it becomes necessary that you sort the keys according to the values of each key and then use that dictionary.

We can easily do that using `sorted` function using the `key` argument –

scores = {
    "India": 150, 
    "Australia": 130, 
    "England": 120, 
    "New Zealand": 80, 
    "South Africa": 135
}

sorted_scores = dict(sorted(scores.items(), key=lambda kv: kv[1]))
print(sorted_scores)
# {'New Zealand': 80, 'England': 120, 'Australia': 130, 'South Africa': 135, 'India': 150}

Conclusion

In this blog, we covered the basics of Python dictionaries, including creation, access, updates, merging, and sorting. With these you will have stronger understanding of dictionaries and can work easily with them without breaking your system.

Dictionaries are powerful, and as you work with them more, you’ll discover additional use cases and techniques. Keep experimenting and learning—happy coding! 💻

Liked this blog? Want to read my other blogs from The Startup Coder? Start from here.

References:

Hi, I’m Arup—a full-stack engineer at Enegma and a blogger sharing my learnings. I write about coding tips, lessons from my mistakes, and how I’m improving in both work and life. If you’re into coding, personal growth, or finding ways to level up in life, my blog is for you. Read my blogs for relatable stories and actionable steps to inspire your own journey. Let’s grow and succeed together! 🚀

Leave a Reply

Your email address will not be published. Required fields are marked *