How to Use If/Else in a Dictionary Comprehension

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.

Dictionary comprehension with if statements using list comprehension

You're right: your test always passes because one condition is true. You need all the conditions to be true.

You could use all to get the proper behaviour:

{k: v for k, v in all_dict.items() if all(v[feature] == match_dict[feature] for feature in feature_list)}

note that if match_list keys are the same as feature_list, it's even simpler, just compare dictionaries:

r = {k: v for k, v in all_dict.items() if v == match_dict}

(or compute a filtered match_dict with the features you require first. Performance will be better)

if-else in a dictionary comprehension

That's because the conditional applies for the value of the dictionary, not for the key value pair, i.e it is evaluated as:

row = {k: (converters[k](v) if k in converters else k:v) for k,v in row.items()}

and k:v is not syntactically valid here, it's only valid inside a pair of curly brackets or in a function signature (so, you could place k:v in brackets and fix the SyntaxError but, that changes the end result).

The solution is to simply supply the value in the conditional since that is what changes:

row = {k: converters[k](v) if k in converters else v for k,v in row.items()}

Another option, of course, is to instead supply tuples to the dict constructor:

row = dict((k, converters[k](v)) if k in converters else (k,v) for k,v in row.items())

How do I include for loops and if statements in dictionary comprehension?

Dict = {i: 1 if i < 5 else 0 for i in range(11)}

single line if else in python dictionary comprehension method

You are using a conditional expression. It can only be used in places that accept expressions.

In a dictionary comprehension, the key and value parts are separate expressions, separated by the : (so the : character is not part of the expressions). You can use a conditional expression in each one of these, but you can't use one for both.

You only need to use it in the value part here:

{d[i]: 0 if i == 3 else True for i in range(4)}

However, you'll get a KeyError exception because the d dictionary has no 0, 1, and 2 keys.

See the Dictionary displays section of the expression reference documentation:

dict_display       ::=  “{” [key_datum_list | dict_comprehension] “}”
[...]
dict_comprehension ::= expression “:” expression comp_for

[...]

A dict comprehension, in contrast to list and set comprehensions, needs two expressions separated with a colon followed by the usual “for” and “if” clauses.

Use else in dict comprehension

You can't use the key-value pair in the else part of ternary conditional like so.

Do this instead:

new_dict = {k: d1[k] if k in d1 else d2[int(k)]  for k in 'abc123'}
# ^^<- make value d2[int(k)] on else
print(new_dict)
#{'2': 2, '1': 1, 'b': 'b', 'a': 'a', 'c': 'c', '3': 3}

Note that if k in d1 checks if k is a key in the dictionary d1. No need to call the keys method.

In python how does if-else and for in a dictionary comprehension work

Does a translation help?

data = {}
for n in graph.by_tag('value'):
if n.content:
data[n.attributes['xid']] = float(n.content)
else:
data[n.attributes['xid']] = np.nan

Python nested dict comprehension with if else

This abomination will do:

{fk: None
for k, v in my_dict.items()
for fk in ([k] if v is None else (k + fv for fv in v))}

If the value is None, you just want the key.

If the value is not None, you want a list of each value concatenated with the key.

Homogenise that to always returning a list, either of one key or multiple:

[k] if v is None else [k + fv for fv in v]

Then you're looking at a "simple" nested comprehension:

{k: None for k in [['a'], ['b'], ['c1', 'c2', 'c3']] for fk in k}

if else in dictionary comprehension

if/else ternaries applies to a given value. In that case, that is the expression 1 or '1' not e:1 or e:'1'.

d = {e:1 if isinstance(b, int) else '1' for e,b in enumerate(a)}


Related Topics



Leave a reply



Submit