[英]Convert a list of tuples (3 elements each) to a dict {a: {b: set(c)}}
I have a list of 3-element tuples, such as [(a1, b1, c1), (a2, b2, c2), (a2, b2, c3)]
.我有一个 3 元素元组列表,例如[(a1, b1, c1), (a2, b2, c2), (a2, b2, c3)]
。
I want to convert the list of tuples to a dict like我想将元组列表转换为像这样的字典
{a1: {b1: set(c1)}, a2: {b2: set (c2, c3)}}
Essentially, the c
needs to be put into a set .本质上, c
需要放入 set 。
How to write a beautiful piece of code for this?如何为此编写一段漂亮的代码?
Here is my current code:这是我当前的代码:
s = {}
for a,b,c in abc:
s.setdefault(a, {}).setdefault(b, set()).add(c)
You can use collections.defaultdict
, which will automatically create default values for missing keys, to do this:您可以使用collections.defaultdict
,它会自动为缺少的键创建默认值,以执行此操作:
>>> from collections import defaultdict
>>> structure = defaultdict(lambda: defaultdict(set))
>>> for a, b, c in ['foo', 'bar', 'baz']:
structure[a][b].add(c)
>>> structure
defaultdict(<function <lambda> at 0x02D16F30>,
{'b': defaultdict(<type 'set'>, {'a': set(['r', 'z'])}),
'f': defaultdict(<type 'set'>, {'o': set(['o'])})})
Note the use of lambda
;注意lambda
的使用; the argument to each defaultdict
must be a callable returning the default value to use for missing keys.每个defaultdict
的参数必须是可调用的,返回用于缺少键的默认值。 However, a slightly simpler structure would make your life easier.然而,稍微简单的结构会让你的生活更轻松。 With {(a, b): set([c1, c2, ..]), ...}
you could use defaultdict(set)
or justdict.setdefault
:使用{(a, b): set([c1, c2, ..]), ...}
你可以使用defaultdict(set)
或者只是dict.setdefault
:
>>> structure = {}
>>> for a, b, c in ['foo', 'bar', 'baz']:
structure.setdefault((a, b), set()).add(c)
>>> structure
{('b', 'a'): set(['r', 'z']), ('f', 'o'): set(['o'])}
Note that setdefault
could also be used for the first approach, but:请注意, setdefault
也可以用于第一种方法,但是:
structure.setdefault(a, dict()).setdefault(b, set()).add(c)
is rather less readable than:比以下内容更难读:
structure[a][b].add(c)
You can do this using .setdefault
.您可以使用.setdefault
执行此操作。 It creates new keys and assigns default value, so that we can create any level of dictionary in one statement.它创建新键并分配默认值,以便我们可以在一个语句中创建任何级别的字典。 Code:代码:
tuple_list = [(a1, b1, c1), (a2, b2, c2), (a2, b2, c3)]
new_dict = {}
for grp in tuple_list:
new_dict.setdefault(grp[0], {}).setdefault(grp[1], set()).add(grp[2])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.