I'm trying to invert a dictionary. In the case of many keys having the same value, the new key (old value) should associate with a set of the new values (old keys). I solved the problem, but I'm trying to refactor using dictionary comprehension, and some helper methods.
def has_unique_value(k):
return d.values().count(d[k]) == 1
def keys_with_same_value_as_key(k):
return set([key for key in d.keys() if d[key] == d[k]])
print( {d[k]:k if has_unique_value(k) else d[k]:keys_with_same_value_as_key(k) for k in d.keys()} )
However, this raises a syntax error
print( {d[k]:k if has_unique_value(k) else d[k]:keys_with_same_value_as_key(k) for k in d} )
^
SyntaxError: invalid syntax
Hopefully the alignment in that code works right. It should point to the second :
, in the else
clause. Any idea what's up here? I've tried as many forms of parenthesizing as I can conceive.