In this Python Dictionaries article we want to learn about Mastering Python Dictionaries, Python dictionaries are powerful data structures that allow you to store and retrieve key value pairs. in this article we want to talk about fundamentals concepts of Python dictionaries and provides tips and tricks to help you master working with them.
What are Dictionaries in Python ?
In Python a dictionary is a collection of unordered key value pairs. each key is unique in dictionary and maps to a value. Dictionaries are implemented as hash tables which provides efficient lookup and insertion operations.
Mastering Python Dictionaries
So now let’s start our example from creating Python Dictionaries, you can create a dictionary in Python using curly braces {} or dict() constructor.
1 2 |
my_dict = {'name': 'geekscoders.com', 'age': 25, 'city': 'New York'} print(my_dict) |
This will be the result
You can access the value of a dictionary using its key.
1 2 |
my_dict = {'name': 'geekscoders.com', 'age': 25, 'city': 'New York'} print(my_dict['name']) |
This will be the result
If the key is not present in the dictionary, KeyError will be raised. so you can also use get() method to access the value of a key. get() method returns None if the key is not present in the dictionary.
1 2 3 |
my_dict = {'name': 'geekscoders.com', 'age': 25, 'city': 'New York'} print(my_dict.get('name')) # Output: geekscoders.com print(my_dict.get('gender')) # Output: None |
You can add a new key value pair to a dictionary like this:
1 |
my_dict['gender'] = 'Male' |
You can remove a key value pair from a dictionary using del statement:
1 2 3 |
my_dict = {'name': 'geekscoders.com', 'age': 25, 'city': 'New York'} del my_dict['age'] print(my_dict) |
This will be the result
You can also use pop() method to remove a key value pair and return its value. pop() method takes key as its argument.
1 2 3 4 |
my_dict = {'name': 'geekscoders.com', 'age': 25, 'city': 'New York'} age = my_dict.pop('age') print(age) print(my_dict) |
This is the result
You can loop through a dictionary using for loop. by default loop iterates over keys of the dictionary.
1 2 3 |
my_dict = {'name': 'geekscoders.com', 'age': 25, 'city': 'New York'} for key in my_dict: print(key, my_dict[key]) |
This is the result
You can also use items() method to loop through both keys and values of a dictionary.
1 2 3 |
my_dict = {'name': 'geekscoders.com', 'age': 25, 'city': 'New York'} for key, value in my_dict.items(): print(key, value) |
This will be the output
Learn More on Python Dictionaries
- Understanding Basics of Python Dictionaries
- Advance Python Dictionary Techniques
- Python Dictionary Manipulation
So we can say that Python dictionaries are an important and useful data structure in Python that you should master as Python programmer. by understanding fundamentals concepts of dictionaries and practicing with them, you can efficiently store and retrieve key value pairs in your Python programs.