PYTHON DICTIONARY:
A dictionary is a built-in data structure that stores key-value pairs. It is denoted by curly braces {} and each key-value pair is separated by a colon :. Here’s an example of creating a dictionary in Python:
# Creating a dictionary
person = {"name": "John", "age": 30, "city": "New York"}
# Accessing values in a dictionary
print(person["name"]) # Output: John
print(person["age"]) # Output: 30
In this example, we create a dictionary named person with three key-value pairs: “name”: “John”, “age”: 30, and “city”: “New York”. We can access the values of each key by using the square bracket notation followed by the key name.
Python dictionaries are mutable, which means we can add, remove, or modify key-value pairs after the dictionary is created. Here are some examples of modifying a dictionary:
# Adding a new key-value pair
person["occupation"] = "Engineer"
print(person) # Output: {"name": "John", "age": 30, "city": "New York", "occupation": "Engineer"}
# Modifying an existing value
person["age"] = 35
print(person) # Output: {"name": "John", "age": 35, "city": "New York", "occupation": "Engineer"}
# Removing a key-value pair
del person["occupation"]
print(person) # Output: {"name": "John", "age": 35, "city": "New York"}
Python dictionaries also have many built-in methods for working with keys and values, such as keys(), values(), items(), get(), and update(). These methods make it easy to manipulate dictionaries and perform common operations.
Built-in Dictionary Functions & Methods
Python dictionaries come with several built-in functions and methods that make it easy to work with key-value pairs. Here are some of the most commonly used functions and methods:
These functions and methods are powerful tools for manipulating dictionaries in Python, and understanding how they work can help you write more efficient and effective code.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.