kk1957
kk1957

Reputation: 8824

python dictionary with list as values

I have a list of string like

vals = ['a', 'b', 'c', 'd',........]

using vals, I would be making a request to a server with each vals[i]. The server would return me a number for each of the vals.

it could be 1 for 'a', 2 for 'b', 1 again for 'c', 2 again for 'd', and so on. Now I want to create a dictionary that should look like

{ 1: ['a','c'], 2:['b','d'], 3: ['e'], ..... } 

What is the quickest possible way to achieve this? Could I use map() somehow? I mean I can try doing this by storing the results of request in a separate list and then map them one by one - but I am trying to avoid that.

Upvotes: 2

Views: 298

Answers (2)

Martin
Martin

Reputation: 1098

Alternatively, you can use defaultdict from collections like so:

from collections import defaultdict
results = defaultdict(list)
for val in vals:
    i = some_request_to_server(val)
    results[i].append(val)

Upvotes: 2

Andrew Clark
Andrew Clark

Reputation: 208455

The following should work, using dict.setdefault():

results = {}
for val in vals:
    i = some_request_to_server(val)
    results.setdefault(i, []).append(val)

results.setdefault(i, []).append(val) is equivalent in behavior to the following code:

if i in results:
    results[i].append(val)
else:
    results[i] = [val]

Upvotes: 4

Related Questions