Use of dictionary in python


In Python, a dictionary is a collection of key-value pairs, where each key is unique and corresponds to a value. Dictionaries are also known as associative arrays, hash tables, or maps in other programming languages.


Here is an example of a dictionary in Python:

my_dict = {
    "apple": 2.99,
    "banana": 1.99,
    "orange": 0.99,
    "kiwi": 3.49
}

In this example, the my_dict dictionary contains four key-value pairs, where the keys are strings that represent different fruits, and the values are floating-point numbers that represent their prices.


You can access the values in a dictionary by using the keys. For example, to access the price of an apple in the my_dict dictionary, you can do the following:

apple_price = my_dict["apple"]
print("The price of an apple is:", apple_price)  
# Output: The price of an apple is: 2.99

In this example, the value of the apple key is accessed using square brackets and assigned to the apple_price variable.


You can also add, modify, and delete key-value pairs in a dictionary. For example, to add a new key-value pair to the my_dict dictionary, you can do the following:

my_dict["pear"] = 1.49
print(my_dict)  
# Output: {'apple': 2.99, 'banana': 1.99, 'orange': 0.99, 'kiwi': 3.49, 'pear': 1.49}

In this example, a new key-value pair with the key "pear" and the value 1.49 is added to the my_dict dictionary using square brackets.


Dictionaries are very useful when you need to store and retrieve data using a key, especially when the data is not in a sequential order like a list or tuple.

Leave a Reply

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