4 built-in data types
In Python, lists, sets, tuples, and dictionaries are used to store collections of data. Each has different properties and use cases.
- dictionary: an unordered, mutable collection that stores key-value pairs.
It can contain different data types:
✅ Keys must be immutable (like strings, numbers, or tuples)
✅ values can be any data type (including other dictionaries)
✅ Dictionaries are defined using curly braces '{}', with key-value pairs separated by colons ':' and items separated by commas ','
✅ Dictionaries provide efficient lookups based on keys. You can access, add, modify, or remove items using their keys.
Use dictionaries shen data needs to be stored as key-value pairs and when fast lookups are needed.
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}
name = my_dict["name"]
age = my_dict["age"]
city = my_dict["city"]
my_dict['name'] # Alice
print(f"{name} is {age} years old and she lives in {city}") # Alice is 25 years old and she lives in New York.
name, age, height = employee
print(f"{name.title()} is {age} years old and {height}\" tall.") # John Doe is 30 years old and 5.9" tall.
# adding new key-value pairs
my_dict["country"] = "USA" # {'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}
# remove the key-value pair and return the value associated with the key
my_dict.pop("country") # USA
# delete key-value pair
del my_dict["city"] #
print(my_dict)
{'name': 'Alice', 'age': 25}
# loop through the dictionary
for key, value in my_dict.items():
print(f"{key}: {value}") # name: Alice
# age: 25
print(my_dict.keys()) # Get all keys
print(my_dict.values()) # Get all values
print(my_dict.items()) # Get key-value pairs
# dict_keys(['name', 'age'])
# dict_values(['Alice', 25])
# dict_items([('name', 'Alice'), ('age', 25)])
# other examples
person = {
"name": "Irene",
"age": 32,
"city": "New York",
"occupation": "Software Engineer",
"hobbies": ["gardening", "reading", "traveling"]
}
user_profile = {
"username": "Irene32",
"email": "irene@example.com",
"preferences": {"language": "French", "theme": "dark mode"}
}
employees_list = [
{"id": 1001, "name": "Alice Johnson", "position": "Software Engineer", "salary": 85000},
{"id": 1002, "name": "Bob Smith", "position": "Software Engineer", "salary": 92000},
{"id": 1003, "name": "Charlie Brown", "position": "Product Manager", "salary": 105000}
]
# look for software engineers
for employee in employees_list:
if employee["position"] == "Software Engineer":
print(f"{employee['name']} (ID: {employee['id']})") # Alice Johnson (ID: 1001)
# Bob Smith (ID: 1002)
for employee in employees_list:
if employee["position"] == "Data Scientist":
print(f"{employee['name']} (ID: {employee['id']})")
data_scientists_found = True
if not data_scientists_found:
print("No data scientists found.") # No data scientists found.