Introduction
Hey there! Welcome back to our Python tutorial series on CipherTrick.com. In this tutorial, we’re going to take a detailed look at a very powerful data structure in Python – Dictionaries. If you’ve been wondering how to store data in key-value pairs, then dictionaries are the way to go.
Part 1: What are Dictionaries?
A dictionary in Python is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key-value pair. Dictionaries are optimized for retrieving the value when we know the key. Dictionaries are defined by enclosing a comma-separated list of key-value pairs in curly braces {}
.
person = {"name": "Alice", "age": 20, "city": "New York"}
Part 2: Accessing Dictionary Items
You can access the items of a dictionary by referring to its key name, inside square brackets.
print(person["name"]) # Outputs: Alice
Part 3: Changing and Adding Dictionary Items
You can change the value of a specific item by referring to its key name. Also, you can add a new item to a dictionary by using a new index key and assigning a value to it.
# Changing value
person["age"] = 25
# Adding item
person["profession"] = "Engineer"
print(person) # Outputs: {'name': 'Alice', 'age': 25, 'city': 'New York', 'profession': 'Engineer'}
Part 4: Dictionary Methods
Python provides a range of methods that you can use on dictionaries.
- get(): The get() method returns the value for the specified key if it exists.pythonCopy code
age = person.get("age")
- keys(): The keys() method returns a new view of the dictionary’s keys.pythonCopy code
keys = person.keys()
- values(): The values() method returns a new view of the dictionary’s values.pythonCopy code
values = person.values()
- items(): The items() method returns a new view of the dictionary’s items (key-value pairs).pythonCopy code
items = person.items()
- update(): The update() method updates the dictionary with the elements from another dictionary object or from an iterable of key-value pairs.pythonCopy code
person.update({"city": "Boston", "hobby": "Music"})
- pop(): The pop() method removes and returns an element from a dictionary having the given key.pythonCopy code
profession = person.pop("profession")
Conclusion
Dictionaries are a powerful tool in Python that allow you to associate pairs of elements, the key and its corresponding value. This feature makes them essential for data manipulation, setting configurations, or even building robust applications. In the next tutorial, we will tackle an exciting topic – Functions in Python. So, keep practicing and see you in the next tutorial!