2

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.

0

2 Answers 2

4

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]
Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.