Python FullStack

Python Dictionary And Its Uses

Dictionary in Python

  • Dictionary is a collection of heterogeneous values with key-value pairs.
  • Each key in a dictionary must be unique and immutable and values can be mutable.
  • Dictionaries are defined using curly braces ‘{}’, with key-value pairs separated by colons ‘:’.

why Key Will be Unique ?


Because Dictionaries are typically implemented using hash tables, which rely on a hash function to compute index of each key-value pair in an underlying array.If keys were not unique, It would be impossible to retrieve data when multiple values associated with same key.

Syntax:

my_dict = {‘apple’:3, ‘banana’:2, ‘orange’:4}
print(my_dict)

Example:

# Dictionary representing information about a person

1.person_info = {
“name”: “Raju”,
“age”: 30,
“languages”: [“Python”, “JavaScript”, “Java”],
}

# Accessing values using keys

print(“Name:”, person_info[“name”])
print(“Age:”, person_info[“age”])
print(“Languages:”,(person_info[“languages”][0])

Output :

Name: Raju
Age: 30
Languages: Python

Real time Examples

Storing User Information in a Web Application: In a web application, you might store user information such as username, email, password, etc., in a dictionary where the keys represent the attributes of the user.

Storing Metadata for Files: Dictionaries can be used to store metadata for files such as file names, sizes, types,and modification dates.
Representing a Database Record: When working with databases, you might represent a database record as a dictionary where keys correspond to column names and values correspond to column values.

Leave a Comment

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

Open chat
Need Help?
Hello
Can we Help you?