简体   繁体   中英

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. 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). That would also need to be true for tuples of length more then 2 (eg (2, 3, 4) = (4, 3, 2)).

Using 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(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:

>>> {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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM