字典成元组对

时间:2016-11-24 18:23:01

标签: python python-3.x dictionary set tuples

我想知道是否可以将字典转换为相应键和值的元组,例如这本词典

{A: {B, C}, B: {A, C}, C: {A, B, D}, D: {C}}

将返回与此类似的内容

{(A, B), (A, C), (B, C), (C, D)}

1 个答案:

答案 0 :(得分:2)

当然,只需使用带有嵌套循环的集合理解来生成产品(每个密钥与每个引用的集合中包含的元素):

{(k, v) for k, values in d.items() for v in values}

演示:

>>> d = {'A': {'B', 'C'}, 'B': {'A', 'C'}, 'C': {'A', 'B', 'D'}, 'D': {'C'}}
>>> {(k, v) for k, values in d.items() for v in values}
{('B', 'A'), ('D', 'C'), ('A', 'B'), ('B', 'C'), ('C', 'B'), ('C', 'D'), ('A', 'C'), ('C', 'A')}
>>> from pprint import pprint
>>> pprint(_)
{('A', 'B'),
 ('A', 'C'),
 ('B', 'A'),
 ('B', 'C'),
 ('C', 'A'),
 ('C', 'B'),
 ('C', 'D'),
 ('D', 'C')}