Table of Content

Dictionary



A Python dictionary is a data structure that stores key-value pairs, providing fast access to values based on unique keys. It's defined using curly braces { } and allows for efficient data lookup and organization.


Creation and Initialization:

python
# Creating a dictionary

person = {"name": "John", "age": 30, "city": "New York"}

Accessing Elements:

Look how to access elements in the dictionary.

python
person = {"name": "John", "age": 30, "city": "New York"}
                                        
print(person["name"])
print(person["age"])

Output:

python
John
30

Adding and Modifying Elements:

Let's add and modify our code.

python
# Adding a new key-value pair
person["job"] = "Engineer"

# Modifying an existing value
person["age"] = 35

print(person["job"])
print(person["age"])

Output:

python
Engineer
35

Removing Elements:

Let's remove the elements from our dictionary.

python
# Removing a key-value pair
del person["city"]

print(person)

Output:

python
{"name": "John", "age": 30, "job": "Engineer"}

Length of Dictionary:

Now you know it very well how to check the length of dictionary.

python
# Length of a dictionary
print(len(person))

Output:

python
3

Iterating Over a Dictionary:

Now you know it very well how to check the length of dictionary.

python
# Iterating over keys
for key in person:
    print(key, person[key])

# Iterating over key-value pairs
for key, value in person.items():
    print(key, value)

Output:

python
name John
age 30
city New York
name John
age 30
city New York

In conclusion, tuples in Python are immutable ordered collections of elements, defined using parentheses `()`. They provide a fixed data structure for storing related items together. Although tuples lack the mutability of lists, their immutability offers benefits in terms of performance and data integrity. Tuples are commonly used for representing fixed data sets, function return values, and ensuring data consistency where modification is not required.


Checking Key Existence:

Check if a key exists in a dictionary using "in" keyword.

python
# Checking if a key exists

if "name" in person:
    print("Name exists in the dictionary")

Output:

python
Name exists in the dictionary

In conclusion, dictionaries in Python are versatile data structures that store key-value pairs, providing efficient lookup and manipulation capabilities. They are defined using curly braces { } and consist of unique keys mapped to corresponding values. Dictionaries are commonly used for tasks such as storing structured data, creating lookup tables, and representing metadata. With their ability to store heterogeneous data and support for fast key-based access, dictionaries are essential components in Python programming for managing and organizing data effectively.