简体   繁体   English

带有列表作为值的python字典

[英]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]. 使用vals ,我将使用每个vals [i]向服务器发出请求。 The server would return me a number for each of the vals. 服务器会为我返回每个val的数字。

it could be 1 for 'a', 2 for 'b', 1 again for 'c', 2 again for 'd', and so on. “ a”可能是1,“ b”可能是2,“ c”又是1,“ d”又是2,依此类推。 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? 我可以以某种方式使用map()吗? 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. 我的意思是我可以尝试通过将请求的结果存储在单独的列表中,然后将它们一一对应来进行尝试,但是我想避免这种情况。

The following should work, using dict.setdefault() : 以下应该可以使用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: results.setdefault(i, []).append(val)在行为上等效于以下代码:

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

Alternatively, you can use defaultdict from collections like so: 另外,您可以使用如下collections defaultdict

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM