If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Python, a dictionary is a versatile and powerful data structure that allows you to store a collection of key-value pairs. Dictionaries are also known as associative arrays or hash maps in other programming languages. Dictionaries are defined by enclosing a comma-separated list of key-value pairs within curly braces
{ }
.Here's a brief introduction to dictionaries in Python:
- Creating a Dictionary: You can create a dictionary by defining it with curly braces and specifying key-value pairs separated by colons.
Example:
pythonCopy code
# Dictionary of key-value pairs with strings as keys person = { "name": "John", "age": 30, "city": "New York" } # Dictionary of key-value pairs with integers as keys grades = { 101: "A", 102: "B", 103: "C" } # Mixed data types as values in a dictionary data = { "name": "Alice", "age": 25, "is_student": True, "marks": [90, 95, 85] }
- Accessing Values: You can access the values in a dictionary by using the corresponding key.
Example:
pythonCopy code
person = { "name": "John", "age": 30, "city": "New York" } print(person["name"]) # Output: John print(person["age"]) # Output: 30
- Modifying and Adding Elements: Dictionaries are mutable, so you can change the value associated with a key or add new key-value pairs.
Example:
pythonCopy code
person = { "name": "John", "age": 30, "city": "New York" } person["age"] = 35 # Modify the value for the key "age" print(person) # Output: {'name': 'John', 'age': 35, 'city': 'New York'} person["occupation"] = "Engineer" # Add a new key-value pair print(person) # Output: {'name': 'John', 'age': 35, 'city': 'New York', 'occupation': 'Engineer'}
- Dictionary Methods: Dictionaries come with various built-in methods to perform common operations, such as
keys()
,values()
,items()
,get()
,pop()
,update()
, etc. These methods provide convenient ways to manipulate dictionaries.Example:
pythonCopy code
person = { "name": "John", "age": 30, "city": "New York" } print(person.keys()) # Output: dict_keys(['name', 'age', 'city']) print(person.values()) # Output: dict_values(['John', 30, 'New York']) print(person.items()) # Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New York')]) print(person.get("name")) # Output: John print(person.get("gender")) # Output: None
Dictionaries are widely used for various purposes, such as representing data in key-value pairs, mapping values to unique identifiers, and organizing data for efficient access and retrieval. They are an essential part of Python and are commonly used in many real-world applications.
Comments: 0