Dictionary

Dictionary in Python

In Python, a dictionary is a built-in data structure that allows us to store a collection of key-value pairs. Each key in a dictionary maps to a corresponding value, similar to how words in a dictionary map to their definitions.

Dictionaries are defined using curly braces {}, with each key-value pair separated by a colon : and each pair separated by a comma. For example, we can create a dictionary that maps fruits to their colors like this:

my_dict = {'apple': 'red', 'banana': 'yellow', 'cherry': 'red'}

We can access the value associated with a particular key using square bracket notation:

color = my_dict['apple']

We can also modify the value associated with a key or add a new key-value pair to the dictionary:

my_dict['apple'] = 'green'   # Change the value associated with the 'apple' key
my_dict['pear'] = 'green'    # Add a new key-value pair to the dictionary

We can loop over the keys or values in a dictionary using the keys() and values() methods:

for key in my_dict.keys():
    print(key)

for value in my_dict.values():
    print(value)

We can also loop over both the keys and values using the items() method:

for key, value in my_dict.items():
    print(key, value)

Overall, dictionaries are a powerful data structure in Python that allow us to efficiently store and retrieve data using meaningful keys. They are commonly used in many programming tasks, such as data processing and web development.

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

Share this post
[social_warfare]
VTP Modes
Sequences

Get industry recognized certification – Contact us

keyboard_arrow_up