Ternary Expression In Dictionary Comprehension
Solution 1:
Close!
The following code
d = {'a': 'x', 'b': 'y', 'c': 'x'}
defhas_unique_value(k):
return d.values().count(d[k]) == 1defkeys_with_same_value_as_key(k):
returnset([key for key in d.keys() if d[key] == d[k]])
print( {d[k]:k if has_unique_value(k) else keys_with_same_value_as_key(k) for k in d.keys()} )
Produces
{'y': 'b', 'x': set(['a', 'c'])}
The only difference is the second d[k]:
is removed.
In general, the ternary expression looks like
a = val_if_true if test else val_if_false
not something closer to what you had:
a = val_if_true if test else a = val_if_false
You specify where the value from the ternary expression should go once, at the beginning.
RE: Question in comments
This is still definitely a dictionary comprehension.
It's basically doing the following:
m = {}
for k in d.keys():
orig_key = k
orig_val = d[k]
if has_unique_value(k):
m[orig_val] = orig_key
else:
m[orig_val] = keys_with_same_value_as_key(orig_key)
print m
The only difference is that, in the dictionary comprehension, the m
dictionary is not kept in the namespace (and the variables orig_key
and orig_val
I used to clarify the code never exist).
Solution 2:
The ternary expression can only be applied to one value and not to the equivalent of a dictionary assignment. Try this instead:
{d[k]: k if has_unique_value(k) else keys_with_same_value_as_key(k) for k in d.keys()}
Your first approach would be similar to the following (which does not work):
d[k] = k if k else d[k] = None# doesn't work
Post a Comment for "Ternary Expression In Dictionary Comprehension"