7

I'm using Aiohttp's implementation of multidict(). Take this:

>>> d = MultiDict[('a', 1), ('b', 2), ('a', 3)])
>>> d
<MultiDict {'a': 1, 'b': 2, 'a': 3}>

I want to convert d to a regular dictionary where duplicate key values are appended into a list such as this:

{'a': [1, 3], 'b': 2}

Is there an elegant way to convert this? Other than a loop through items and a lot of logical conditions?

Deik
  • 134
  • 9

1 Answers1

5

It doesnt look like multidicts have an inbuilt function for a straight conversion, but you can use the .keys() function to iterate through the multidict and copy the values into a fresh dictionary.

new_dict = {}
for k in set(multi_dict.keys()):
    new_dict[k] = multi_dict.getall(k)

Two interesting things here - we need to make a set of the multidict keys function call to remove duplicates, and multidicts have a .getall() function that returns a list of all values associated with duplicate keys.

EDIT for single value cases:

new_dict = {}
for k in set(multi_dict.keys()):
    k_values = multi_dict.getall(k)
    if len(k_values) > 1:
        new_dict[k] = k_values
    else:
        new_dict[k] = k_values[0]
PeptideWitch
  • 2,239
  • 14
  • 30
  • 1
    Seems like this make a list of the single value `'b': [2]` rather than the OP's requested format. Maybe that's better ... don't know. – Mark May 18 '21 at 00:43
  • 1
    Problem with this getall() always returns a list. So instead new_dict will look like `{'a': [1, 3], 'b': [2]}` – Deik May 18 '21 at 00:44
  • Good points; I'd tend to think that a dictionary with lists as values is better than a dictionary with values that are a mix of lists/single entries, but OP might have specific downstream code they want to keep. Edited my post with a solution. – PeptideWitch May 18 '21 at 00:47