Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to obtain a dictionary from a set

I have set, some_set = {'A', 'B', 'C'}

I'm looking to turn this into a dictionary like so:
my_dict = {'A':{'B','C'}, 'B':{'A','C'}, 'C':{'A','B'}}
ie a dictionary of sets, where every key is mapped to a set having all elements from the original set except the key itself.

What I have right now:

for letter_1 in some_set
    for letter_2 in some_set:
        if letter_1 not in my_dict.keys():
            my_dict[letter_1] = set()
        if letter_2 != letter_1:
            my_dict[letter_1].add(letter_2)

What I'm looking for: Is this the best way to do it? Would there be a more pythonic way to achieve what I want?

like image 265
Ayush Avatar asked May 29 '26 12:05

Ayush


1 Answers

A simple dictionary comprehension:

>>> some_set = {'A', 'B', 'C'}
>>> my_dict = {k: some_set - {k} for k in some_set}
{'A': {'B', 'C'}, 'B': {'A', 'C'}, 'C': {'A', 'B'}}
>>>
like image 172
AKX Avatar answered Jun 01 '26 01:06

AKX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!