Con*_*ine 3 python dictionary tuples key list
我有以下列表:parent_child_list带有 id 元组:
[(960, 965), (960, 988), (359, 364), (359, 365),
(361, 366), (361, 367), (361, 368), (361, 369),
(360, 370), (360, 371), (360, 372), (360, 373), (361, 374)]
Run Code Online (Sandbox Code Playgroud)
示例:我想打印与 id 960 组合的那些值。这些值是:965、988
我尝试将列表转换为字典:
rs = dict(parent_child_list)
Run Code Online (Sandbox Code Playgroud)
因为现在我可以简单地说:
print rs[960]
Run Code Online (Sandbox Code Playgroud)
但不幸的是我忘记了 dict 不能有双值,所以我只收到 965,而不是得到 965、988 作为答案。
有没有简单的选择来保留双精度值?
非常感谢
小智 5
您可以使用 defaultdict 创建以列表作为其值类型的字典,然后附加值。
from collections import defaultdict
l = [(960, 965), (960, 988), (359, 364), (359, 365), (361, 366), (361, 367), (361, 368), (361, 369), (360, 370), (360, 371), (360, 372), (360, 373), (361, 374)]
d = defaultdict(list)
for key, value in l:
d[key].append(value)
Run Code Online (Sandbox Code Playgroud)