[英]Dictionary whose key is independent on the order of elements it contains
I would like to create a dictionary in Python, whose key would be independent on the order of elements it contains. 我想用Python创建一个字典,它的键将取决于它包含的元素的顺序。 Here is example:
这是示例:
items = {1: 2, 2: 3, 4: 5}
comb = {(key1, key2): 0 for key2 in items.keys() for key1 in items.keys() if key1 != key2}
Outputs: 输出:
{(1, 2): 0, (1, 4): 0, (2, 1): 0, (4, 2): 0, (4, 1): 0, (2, 4): 0}
But I would only like to have: 但我只想拥有:
{(1, 2): 0, (1, 4): 0, (2, 4): 0}
So the key (1, 2) should be equal to (2, 1). 因此,键(1,2)应该等于(2,1)。 That would also need to be true for tuples of length more then 2 (eg (2, 3, 4) = (4, 3, 2)).
对于长度大于2的元组(例如(2,3,4)=(4,3,2)),也必须如此。
Using itertools.combinations
: 使用
itertools.combinations
:
>>> {keys: 0 for keys in itertools.combinations(items, 2)}
{(1, 2): 0, (2, 4): 0, (1, 4): 0}
with dict.fromkeys
(Only use dict.fromkeys
when the value is immutable; the value is shared by all entries): 与
dict.fromkeys
使用(仅当值不可变时才使用dict.fromkeys
;该值由所有条目共享):
>>> dict.fromkeys(itertools.combinations(items, 2), 0)
{(1, 2): 0, (2, 4): 0, (1, 4): 0}
>>> dict.fromkeys(itertools.combinations(items, 3), 0)
{(1, 2, 4): 0}
If you want to have order-independent keys in a general case, you can use frozensets as keys instead of tuples: 如果您希望在一般情况下拥有与顺序无关的键,则可以使用Frozensets作为键而不是元组:
>>> {frozenset((key1, key2)): 0 for key2 in items.keys() for key1 in items.keys() if key1 != key2}
{frozenset({2, 4}): 0, frozenset({1, 2}): 0, frozenset({1, 4}): 0}
For the specific case of the OP, the previously mentioned solution will be better. 对于OP的特定情况,前面提到的解决方案会更好。 However, if there is a need for really order-independent keys, the solution I proposed might be a way to go and more elegant (and faster) than sorting the indices.
但是,如果需要真正与顺序无关的键,那么我提出的解决方案可能是一种方法,并且比对索引进行排序更为优雅(且速度更快)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.