简体   繁体   中英

Match keys to values in dictionary in python

Say for example this is my dictionary:

my_dict= {"0" : {"1","2","3"},"1":{"2"},"2":{"3"}}

I want to pair these values and keys together in every instance. What would be the most efficient way to add each key, into the corresponding values key to make the pair. Sorry if my wording is overly confusing. Essentially, I want it to become:

my_dict={"0" : {"1","2","3"}, "1" : {"0","2"}, "2" : {"0","1","3"}, "3" : {"0","2"}}

This way, every number is paired in both key and value form. If it's still unclear what I am asking, just let me know and I will try to explain clearer.

Another way I could try to explain it is imagine my current dictionary as the matchings in a digraph, and I want to convert it to show the matchings in an undirected graph.

You can use collections.defaultdict for this . Example -

from collections import defaultdict
result = defaultdict(set)
for key,value in my_dict.items():
    result[key].update(value)
    for elem in value:
        result[elem].add(key)

Here you create a defaultdict with values as set , then for every key in your original dictionary, update that for the same key in the result defaultdict. Then iterating over every element in the value (set) , you add the key as the value for the element in the result defaultdict.

Demo -

>>> my_dict= {"0" : {"1","2","3"},"1":{"2"},"2":{"3"}}
>>> from collections import defaultdict
>>> from collections import defaultdict
>>> result = defaultdict(set)
>>> for key,value in my_dict.items():
...     result[key].update(value)
...     for elem in value:
...         result[elem].add(key)
...
>>> pprint.pprint(result)
{'0': {'1', '2', '3'},
 '1': {'2', '0'},
 '2': {'0', '1', '3'},
 '3': {'2', '0'}}

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