Skip to main content

Command Palette

Search for a command to run...

Python Dictionaries - Access, delete elements 🐍

Updated
β€’2 min read
Python Dictionaries - Access, delete elements 🐍
N

Seasoned JavaScript Developer who loves to explore other programming languages like Python. A problem solver, tech lover by heart. Loves reading booking, and cooking. πŸ€©πŸš€πŸ”¬

In the last article, we had seen how we can create a dictionary and access an element in it. Today we will dive deep into the main data structure in Python known as Dictionary.

Accessing an element πŸ’‘

The element in the dictionary can be accessed through the square brackets nomenclature.

dict = {"name": "Nitin", "age": 34, "gender": "male"}

dict["name"]
Result -> Nitin

What if you are trying to access an element that is not in the dictionary?

dict = {"name": "Nitin", "age": 34, "gender": "male"}

dict["address"]
Result -> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'address'

In the above example, the address is not in the dictionary because we are trying to access it from the square brackets.

But we can also leverage the get method to access the dictionary key

dict = {"name": "Nitin", "age": 34, "gender": "male"}
dict.get("name")
Result -> 'Nitin'

Delete an element with del method πŸ’‘

dict = {"name": "Nitin", "age": 34, "gender": "male"}
del(dict["name"])
print(dict)
Result -> {"age": 34, "gender": "male"}

Delete the dictionary πŸ’‘

dict = {"name": "Nitin", "age": 34, "gender": "male"}
del(dict)
print(dict)
Result -> <class 'dict'>

In order to delete the dictionary you have to mention the dictionary variable name in the del method.

Find the length πŸ’‘

Finding the length of the dictionary is quite simple.

dict = {"name": "Nitin", "age": 34, "gender": "male"}
len(dict)
Result -> 3

Check if the key exists πŸ’‘

Not so difficult.

dict = {"name": "Nitin", "age": 34, "gender": "male"}
print("name" in dict)
Result -> True

The boolean would be returned when you try to check the key in the dictionary.

Easy to understand? πŸ’‘

A dictionary contains

  • unique keys

  • a key can have different types of values like number, string, boolean etc.

  • we can access dictionary elements with multiple approaches

This would look similar to an object in JavaScript

Conclusion πŸ“—

There are more posts on the way related to the tuples...So keep reading.

Thanks in advance for reading this article...πŸš€

I am more than happy to connect with you on

You can also find me on

More from this blog

N

nitinreddy3

43 posts

Seasoned JavaScript Developer who loves to explore other programming languages like Python. A problem solver, tech lover by heart. Loves reading booking, and cooking. πŸ€©πŸš€πŸ”¬