A multidict (or multi-dictionary) is a data structure in Python that extends the capabilities of a regular dictionary. A multidict can store multiple values for the same key, while a regular dict can only store one value for each key.
Python does not have a built-in datatype of multidict. To use a multidict data structure in Python, we need to import it from the 3rd-party library multidict. In this tutorial, we will learn the basics, installation, and demonstrate CRUD (Create, Read, Update, Delete) operations using multidict data structure.
from multidict import MultiDict
# Creating a Multidict
multidict = MultiDict()
multidict['key'] = 'value'
multidict.add('key', 'another_value')
# Accessing values in Multidict
value = multidict['key']
values = multidict.getall('key')
# Updating values in Multidict (overwrites the existing key-value entry)
multidict.update({'new_key': 'new_value'})
# Deleting values from Multidict
del multidict['key']
multidict.popall('new_key')
# Clearing Multidict
multidict.clear()
1. What is Multidict?
A multidict is like a special kind of dictionary in Python that allows us to have more than one value for the same key. In a regular dictionary, each key can have only one value, but with a multidict, a key can be associated with multiple values.
Imagine we have a list of your favorite colors. In a regular dictionary, you can only associate one color with each day:
colors = {'Monday': 'Blue', 'Tuesday': 'Red', 'Wednesday': 'Green'}
But with a multidict, you can have multiple colors for the same day:
from multidict import MultiDict
colors = MultiDict()
colors.add('Monday', 'Blue')
colors.add('Monday', 'Yellow')
colors.add('Tuesday', 'Red')
colors.add('Wednesday', 'Green')
Here, ‘Monday’ has two colors associated with it (‘Blue’ and ‘Yellow’). It’s like having a bag where you can put many items with the same tag.
Now, let’s take a step-by-step approach to understand how to use and manipulate multidicts.
2. Installation and Import
Before using multidict, you need to install it. Open your terminal or command prompt and run:
pip install multidict
Once installed, you can import it into your Python script or interactive environment:
from multidict import MultiDict
3. Basic CRUD Operations on a MultiDict
Let’s understand how to interact with a multidict and perform various operations.
3.1. Creating a Multidict
Creating a multidict involves initializing an empty one or with specified key-value pairs.
multidict = MultiDict()
multidictWithItems = MultiDict([('key', 'value1'), ('key', 'value2'), ('new_key', 'value3')])
3.2. Adding Items to MultiDict
We can add items to a multidict using the following 3 methods:
Methods | Description |
---|---|
multidict[‘key’] = ‘value’ | Assigns the value to the specified key. Overwriting any previous entry. |
multidict.add(‘key’, ‘value’) | Appends the value to the existing values for the specified key. |
multidict.setdefault(‘key’, ‘default_value’) | If key is in the dictionary, return its first value. If not, insert key with a value of default and return default. The value of default defaults to None . |
Let’s understand with the following example.
from multidict import MultiDict
multidict = MultiDict()
multidict['key'] = 'value' # <MultiDict('key': 'value')>
multidict.add('key', 'another_value') # <MultiDict('key': 'value', 'key': 'another_value')>
multidict.setdefault('key_default', 'default_value') # <MultiDict('key': 'value', 'key': 'another_value', 'key_default': 'default_value')>
3.3. Accessing Values in Multidict
Multidict provides several approaches to fetch the information stored under specific keys, providing flexibility in handling different use cases.
Method | Description |
---|---|
get(key[, default]) | Return the first value for the given key if present; otherwise, return the default (or None if the default value is not provided). |
getone(key[,default]) | Return the first value for the given key if present; otherwise, return the default (or raise KeyError if the default value is not provided). |
getall(key[, default]) | Return a list of all values for the given key if present; otherwise, return the default (or raise KeyError if the default value is not provided). |
multidict[key] | Return the first value for the given key if present; otherwise, raise KeyError. |
For example, consider a multidict
containing information about fruits:
from multidict import MultiDict
multidict = MultiDict()
multidict.add('fruit', 'apple')
multidict.add('fruit', 'banana')
multidict.add('fruit', 'orange')
print(multidict['fruit']) # apple
print(multidict.get('fruit', default='No fruit')) # apple
print(multidict.getone('fruit', default='No fruit')) # apple
print(multidict.getall('fruit', default='No fruit')) # ['apple', 'banana', 'orange']
3.4. Updating Value of an Existing Key
The multidict.update() method updates the dictionary with the key/value pairs from the argument key-value pair, overwriting existing keys and values.
multidict = MultiDict()
multidict['key'] = 'value'
multidict.add('key', 'another_value')
multidict.update({'key': 'new_value'}) # Overwrites previous entry
print(multidict) # <MultiDict('key': 'new_value')>
Suppose, we want to update an existing value for a specified key in the multidict, then we need to modify the entry itself and overwrite the previous entry completely. We cannot selectively update a value (from multiple values) using any builtin method.
multidict['key'] = 'value'
multidict.add('key', 'another_value')
update_key = 'key'
existing_value = 'another_value'
new_value = 'new_value'
if update_key in multidict:
values = multidict.getall(update_key)
if existing_value in values:
index_to_update = values.index(existing_value)
values[index_to_update] = new_value
multidict.update({update_key: values})
print("Updated Multidict:", multidict) # <MultiDict('key': ['value', 'new_value'])>
3.5. Deleting Values from MultiDict
We can delete entries from a multidict in the following ways:
- Delete an entry completely by using del statement.
- Using clear() method which completely empties the dictionary.
- Remove an entry using one of the pop() methods that may return the value associated with the key.
Method | Description |
---|---|
pop(key[, default]) popone(key[, default]) | If key is in the dictionary, remove it and return its the first value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised. |
popall(key[, default]) | If key is in the dictionary, remove all occurrences and return a list of all values. If key is not found and the default is provided return default. If default is not given and key is not in the dictionary, a KeyError is raised. |
popitem() | Remove and return an arbitrary (key, value) pair from the dictionary.If the dictionary is empty, it raises a KeyError . |
multidict['key'] = 'value'
multidict.add('new_key', 'new_value')
del multidict['key']
value = multidict.pop('new_key', 'default_value')
multidict.clear()
4. Conclusion
In this Python tutorial, we explored the multidict data structure in Python which have the ability to store multiple values for a single key. We learned how to install, import, and perform basic CRUD operations using multidicts.
Happy Learning !!
Comments