将可变长度元组列表转换为字典

cod*_*e47 3 python python-2.7 python-3.x

我有一个可变长度元组列表.如何将其转换为字典?

tup = [ ("x", 1), ("x", 2, 4), ("x", 3), ("y", 1), ("y", 2), ("z", 1), ("z", 2, 3) ]  
Run Code Online (Sandbox Code Playgroud)

使用理解时,我得到以下错误

{key: [i[1:] for i in tup if i[0] == key] for (key, value) in tup}  
Run Code Online (Sandbox Code Playgroud)

错误:

ValueError
Traceback (most recent call last)
>ipython-input-26-bedcc2e8a704< in module()
----> 1 {key: [i[1] for i in tuplex if i[0] == key] for (key, value) in tuplex}  
>ipython-input-26-bedcc2e8a704< in dictcomp((key, value))
----> 1 {key: [i[1] for i in tuplex if i[0] == key] for (key, value) in tuplex}  
ValueError: too many values to unpack
Run Code Online (Sandbox Code Playgroud)

预期产量:

{'x': [1, 2, 4, 3], 'y': [1, 2], 'z': [1, 2, 3]} 
Run Code Online (Sandbox Code Playgroud)

sli*_*der 7

这似乎不是列表理解的任务.你可以使用一个简单的for循环,使用字典的setdefault方法将键的默认值设置为空列表,然后extend使用该元组中的值设置该列表:

tup = [ ("x", 1), ("x", 2, 4), ("x", 3), ("y", 1), ("y", 2), ("z", 1), ("z", 2, 3) ]

res = {}
for k, *rest in tup:
    res.setdefault(k, []).extend(rest)

print(res)
# {'y': [1, 2], 'x': [1, 2, 4, 3], 'z': [1, 2, 3]}
Run Code Online (Sandbox Code Playgroud)

对于Python 2.7,我认为你不能解压这样的元组,所以你可以尝试类似的东西:

for t in tup:
    res.setdefault(t[0], []).extend(t[1:])
Run Code Online (Sandbox Code Playgroud)