MicroPython, just like Python, supports dictionaries, which are a built-in data type used to store data values in key-value pairs. A dictionary in MicroPython is unordered, mutable (can be changed), and indexed by keys.
Dictionaries allow you to access elements by keys rather than by their position (index) as you would with a list or tuple. This tutorial will walk you through how to use dictionaries in MicroPython, with multiple code examples to illustrate different aspects of their usage.
Table of Contents:
1. What is a Dictionary?
A dictionary is a collection of key-value pairs, where each key is unique. You can think of it as a real-world dictionary where words (keys) are associated with definitions (values).
Syntax:
dictionary = {key1: value1, key2: value2, key3: value3}
2. Creating a Dictionary
You can create a dictionary in MicroPython in several ways.
Example 1: Empty Dictionary
# Creating an empty dictionary my_dict = {} Example 2: Dictionary with Initial Values # Dictionary with some initial values person = { 'name': 'Alice', 'age': 30, 'city': 'New York' }
3. Accessing Values
You can access the value associated with a key using square brackets [] or the get() method.
Example 1: Using Square Brackets
# Accessing a value by its key print(person['name']) # Output: Alice Example 2: Using get() Method # Accessing a value using get() print(person.get('age')) # Output: 30 # Using get() with a default value if the key is not present print(person.get('address', 'Not Found')) # Output: Not Found
4. Adding and Updating Values
You can add new key-value pairs or update existing ones by assigning values to a key.
Example 1: Adding New Items
# Adding a new key-value pair person['address'] = '123 Main St' print(person)
Example 2: Updating Existing Items
# Updating an existing value person['age'] = 31 print(person)
5. Removing Items
You can remove key-value pairs from a dictionary using pop(), popitem(), or del.
Example 1: Removing a Specific Item using pop()
# Removing a specific key-value pair person.pop('city') print(person)
Example 2: Removing the Last Inserted Item using popitem()
# Removing the last added key-value pair person.popitem() print(person)
Example 3: Removing an Item using del
# Using del to remove a key-value pair del person['age'] print(person)
6. Looping Through a Dictionary
You can loop through the keys, values, or both in a dictionary using for loops.
Example 1: Looping Through Keys
for key in person: print(key) Example 2: Looping Through Values for value in person.values(): print(value) Example 3: Looping Through Key-Value Pairs for key, value in person.items(): print(f"{key}: {value}")
7. Useful Dictionary Methods
len() – Returns the number of key-value pairs in the dictionary.
keys() – Returns a view object containing the keys of the dictionary.
values() – Returns a view object containing the values of the dictionary.
items() – Returns a view object containing the key-value pairs of the dictionary.
clear() – Removes all items from the dictionary.
copy() – Returns a shallow copy of the dictionary.
Example 1: Using keys(), values(), and items()
# Getting all keys print(person.keys()) # Getting all values print(person.values()) # Getting all key-value pairs print(person.items())
Example 2: Using clear()
# Clearing the dictionary person.clear() print(person) # Output: {}
Example 3: Using copy()
# Creating a copy of the dictionary new_person = person.copy() print(new_person)
Complete Example: Working with a Dictionary
# Creating a dictionary person = { 'name': 'Bob', 'age': 25, 'city': 'London' } # Access a value print("Name:", person['name']) # Add a new key-value pair person['job'] = 'Engineer' # Update an existing value person['age'] = 26 # Remove a key-value pair person.pop('city') # Loop through dictionary items for key, value in person.items(): print(f"{key}: {value}") # Copy the dictionary new_person = person.copy() print("New Person Dictionary:", new_person) # Clear the dictionary person.clear() print("Person after clearing:", person)
Conclusion
Dictionaries in MicroPython are extremely useful when you need to store and manage data in key-value pairs. They provide efficient lookup times and can be dynamically modified at runtime.
The examples in this tutorial cover most of the fundamental operations, but dictionaries can also be used in more advanced scenarios, such as in combination with lists or for more complex data structures.