Open In App

Convert ImmutableMultiDict with duplicate keys to list of lists in Python

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.






# 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:




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. 


Article Tags :