Extract specific values from a multidict to a list
Example 1: Using getall()
This method returns the values associated with a particular key of Multidict. We need to pass the key whose values are desired as a parameter to the method. The method returns a list of values for the key. It will throw a ‘KeyError’ if the specified key is not found.
Python3
# Import the Multidict library import multidict # Declare a Multidict structure # using the Multidict class d = multidict.MultiDict([( 'a' , 1 ), ( 'b' , 2 ), ( 'b' , 3 ), ( 'c' , 5 ), ( 'd' , 4 ), ( 'c' , 7 )]) # Fetch values for key 'b' in a # list using getall(k) method values_for_keyB_list = d.getall( 'b' ) # Print the list of values print ( "Key B values:" , values_for_keyB_list) # Fetch values for key 'c' in a # list using getall(k) method values_for_keyC_list = d.getall( 'c' ) # Print the list of values print ( "Key C values:" , values_for_keyC_list) |
Output:
Key B values: [2, 3] Key C values: [5, 7]
Example 2: Using popall()
This method returns the values associated with a particular key of Multidict. If the key specified, is in a Multidict structure then it removes all occurrences of the key and returns a list of values of the key. It throws a ‘KeyError’ if the specified key is not found.
Python3
# Import the package Multidict import multidict # Create multidict structure using # the Multidict class d = multidict.MultiDict([( 'a' , 1 ), ( 'b' , 2 ), ( 'b' , 3 ), ( 'c' , 5 ), ( 'd' , 4 ), ( 'c' , 7 )]) # Use the popall(k) method to # fetch a list of all # values associated with key 'c' pop_list_of_key_c = d.popall( 'c' ) # print the popped values print ( "Pop out values of key C:" , pop_list_of_key_c) # After popping the key values, # print the Multidict structure print ( "Multidict after popping key C:" , d) |
Output:
Pop out values of key C: [5, 7]
Multidict after popping key C: <MultiDict(‘a’: 1, ‘b’: 2, ‘b’: 3, ‘d’: 4)>
Extract multidict values to a list in Python
The Multidict, is a dictionary-like structure, having key-value pairs, but the ‘same key’ can occur multiple times, in the collection. The features of a Multidict in Python are as follows:
- The insertion order of the collection is maintained.
- Multiple values in the collection can have the same key.
- The keys are stored as a ‘string’.
Installation
pip install multidict