Getting Started with Python (Part 8-2): Working with Multiple Data – Tuples, Sets, and Dictionaries
Source: Dev.to
Working with Multiple Data – Tuples, Sets, and Dictionaries
Tuples
Tuples are similar to lists but are immutable, meaning their values cannot be changed after creation.
member = ("Maruko", "Tama", "Maruo")
member[0] = "Batsuko" # Error
member[1] = "Pochi" # Error
member[2] = "Batsuo" # Error
Use tuples when you need data that must never be altered.
Sets
Sets are unordered collections that automatically remove duplicate values. They are defined with curly braces {}.
member = {"Maruko", "Noguchi", "Tama", "Noguchi", "Maruo", "Noguchi"}
print(member)
# {'Noguchi', 'Maruko', 'Maruo', 'Tama'}
Because sets have no order, you cannot access elements by index (e.g., member[0]).
Dictionaries
Dictionaries store data as key–value pairs. Access a value by specifying its key.
member = {"maruchan": "Maruko", "tama": "Tama", "maruo": "Maruo"}
print(member)
# {'maruchan': 'Maruko', 'tama': 'Tama', 'maruo': 'Maruo'}
# Access values by key
print(member["maruchan"]) # Maruko
print(member["tama"]) # Tama
print(member["maruo"]) # Maruo
# Update values by key
member["tama"] = "Pochi"
member["maruo"] = "Batsuo"
print(member)
# {'maruchan': 'Maruko', 'tama': 'Pochi', 'maruo': 'Batsuo'}
Important Dictionary Methods
-
keys()– returns a view of all keys.member = {"maruchan": "Maruko", "tama": "Tama", "maruo": "Maruo"} print(list(member.keys())) # ['maruchan', 'tama', 'maruo'] -
values()– returns a view of all values.print(list(member.values())) # ['Maruko', 'Tama', 'Maruo'] -
items()– returns a view of(key, value)tuples.print(list(member.items())) # [('maruchan', 'Maruko'), ('tama', 'Tama'), ('maruo', 'Maruo')]
Thank you for reading! In the next article, we’ll explore loops and iteration. Stay tuned! 🚀