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 all the values and their keys. However, when I try to do it, it only gets the first symbol key value pair and ignores the other one.
for k in params:
print(params.get(k))
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.
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']