In this article, we are going to see how to convert ImmutableMultiDict with duplicate keys to a list of lists using Python.
Using Werkzeug Python
Werkzeug is a WSGI utility library. WSGI is a protocol or convention that assures that your web application can communicate with the webserver and, more crucially, that web apps can collaborate effectively. To convert an ImmutableMultiDict with duplicate keys to a list of lists, we’ll use one of its function to create ImmutableMultiDict.
We can use the pip command to install the werkzeug library by opening a command line and typing the following command –
pip install werkzeug
Examples 1:
So, initially, we’ll create an immutableMultiDict with duplicate keys using the werkzeug library’s datastructures class, followed by the ImmutableMultiDict() function. After building ImmutableMultiDict, we’ll utilize one of its methods, lists(), to return a generator object, which we’ll convert to a list using the list function.
Python3
# Importing library from werkzeug.datastructures import ImmutableMultiDict d = ImmutableMultiDict([( 'Subject' , 'Chemistry' ), ( 'Period' , '1st' ), ( 'Period' , '4th' )]) print ( list (d.lists())) |
Output:
[('Subject', ['Chemistry']), ('Period', ['1st', '4th'])]
Example 2:
Python3
from werkzeug.datastructures import ImmutableMultiDict # In this example we are adding gadget and accessories d = ImmutableMultiDict([( 'Gadget' , 'DSLR' ), ( 'Accessories' , 'Lens 18-105mm' ), ( 'Accessories' , 'Lens 70-200mm' ), ( 'Accessories' , 'Tripod stand' )]) list (d.lists()) |
Output:
[(‘Gadget’, [‘DSLR’]), (‘Accessories’, [‘Lens 18-105mm’, ‘Lens 70-200mm’, ‘Tripod stand’])]
Let’s take a look at the code we just wrote one step at a time.
- So, in the first line, we import the ImmutableMultiDict class from the werkzeug module, and we can create ImmutableMultiDict directly using this class. Remember that, unlike standard Dictionaries, MultiDict is a subclass of Dictionary that can have several values for the same key.
- We create ImmutableMultiDict and store it in variable ‘d’ in the second line of code.
- We’re passing two keys with the same name, ‘Period,’ and if it were a normal dictionary, the one that came later would have overwritten the value, and only one could have been stored, not both separate values of the same key name.
- We can now print this ImmutableMultiDict directly, but our goal is to convert it to a list of lists, so we utilize one of its class’s functions .lists() to change the values associated with a single key from tuples to lists. If we want to double-check it, we may use a for loop to print it.
- Finally, we wrapped it in a list function, which stores it in a list, and then we print it.