Understanding Basics of Python Dictionaries

In this Python Dictionaries article we want to learn about Understanding Basics of Python Dictionaries, so Python dictionaries are a type of collection that allows you to store key value pairs. they are similar to lists but instead of being indexed by numerical index like lists, they are indexed by keys, which can be of any hashable data type such as strings, integers or tuples.

 

 

Understanding Basics of Python Dictionaries

For creating a dictionary in Python, you can use curly braces {} or builtin dict() function. 

 

 

For accessing values in a dictionary, you can use the key inside square brackets []. 

 

 

This will be the result

Understanding Basics of Python Dictionaries
Understanding Basics of Python Dictionaries

 

 

If you try to access a key that doesn’t exists, you will get KeyError. to avoid this error you can use get() method, which returns None if the key doesn’t exist, or default value if specified. 

 

 

This will be the result

Understanding Basics of Python Dictionaries
Understanding Basics of Python Dictionaries

 

 

Also you can add new item or modify an existing one in a dictionary, you can use the key inside square brackets [] and assign value to it. 

 

 

To remove an item from a dictionary, you can use the del keyword followed by the key. 

 

 

This will be the result and the age is removed

Dictionary in Python
Dictionary in Python

 

 

Also you can loop through a dictionary, you can use for loop. by default loop will iterate over the keys of the dictionary. 

 

 

This is the result

Python dictionary for Loop
Python dictionary for Loop

 

 

You can also use the items() method to loop over both the keys and values of the dictionary. 

 

 

Learn More on Python Tuples

Leave a Comment