Skip to content Skip to sidebar Skip to footer

Iterate Over Keys And All Values In Multidict

I have a dictionary params = ImmutableMultiDict([('dataStore', 'tardis'), ('symbol', '1'), ('symbol', '2')]) I want to be able to iterate through the dictionary and get a list of

Solution 1:

If I understand you correctly you want to iterate over all keys, including duplicates, right? Then you could use the items(multi=False) method with multi set to True.

Documentation:

items(multi=False)

Return an iterator of (key, value) pairs.

Parameters: multi – If set to True the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the first value of each key.

If I misunderstood you and you want a list of all entries to a single key have a look at jonrsharpe's answer.

Solution 2:

If you read the docs for MultiDict, from which ImmutableMultiDict is derived, you can see:

It behaves like a normal dict thus all dict functions will only return the first value when multiple values for one key are found.

However, the API includes an additional method, .getlist, for this purpose. There's an example of its use in the docs, too:

>>> d = MultiDict([('a', 'b'), ('a', 'c')])
# ...>>> d.getlist('a')
['b', 'c']

Post a Comment for "Iterate Over Keys And All Values In Multidict"