-3

I've tried flip my dict. If some keys have the same value the flipped dict key should be a set()

d = {'a': 1, 'b': 2, 'c': 3, 'd': 3}

output should be:

{1: 'a', 2: 'b', 3: {'c', 'd'}}

I've tried that:

d = {'a': 1, 'b': 2, 'c': 3, 'd': 3}
rev_dict = {}
for k, v in d.items():
    rev_dict.setdefault(v, set()).add(k)
print(rev_dict)

But I got that:

{1: {'a'}, 2: {'b'}, 3: {'c', 'd'}}
  • 1
    You don't check if the key already existed before creating the set (or rather you create the set when the key _doesn't_ already exist, not when it _does_). But this is arguably a more useful result than the one you wanted, as you don't then have to check every time if it's a set or a string. – jonrsharpe Aug 03 '22 at 12:14

2 Answers2

1

just create a new dictionary

newdict = {}
for key, val in d.items():
   if val not in newdict:
        newdict[val] = key
   else:
        newdict[val] = set((*newdict[val], key))
Axeltherabbit
  • 680
  • 3
  • 20
0

Your output is comprised of a mixture of value types - i.e., string and set.

A better model would be to use consistent types. In this case, all sets. Then:

d = {'a': 1, 'b': 2, 'c': 3, 'd': 3}
e = {}

for k, v in d.items():
    e.setdefault(v, set()).add(k)

print(e)

Output:

{1: {'a'}, 2: {'b'}, 3: {'d', 'c'}}
DarkKnight
  • 19,739
  • 3
  • 6
  • 22