Nested dictionary comprehension python

{inner_k: myfunc(inner_v)} isn’t a dictionary comprehension. It’s just a dictionary. You’re probably looking for something like this instead: data = {outer_k: {inner_k: myfunc(inner_v) for inner_k, inner_v in outer_v.items()} for outer_k, outer_v in outer_dict.items()} For the sake of readability, don’t nest dictionary comprehensions and list comprehensions too much.

Is it possible to access current object while doing list/dict comprehension in Python?

No, there is not. A dict comprehension produces a new item for each iteration, and your code needs to produce fewer items (consolidating values). There is no way to access keys produced in an earlier iteration, not without using (ugly, unpythonic) side-effect tricks. The dict object that is going to be produced by the comprehension … Read more

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 … Read more

Alternative to dict comprehension prior to Python 2.7

Use: gw_func_dict = dict((chr(2**i), func) for i, func in enumerate(gwfuncs[:8])) That’s the dict() function with a generator expression producing (key, value) pairs. Or, to put it generically, a dict comprehension of the form: {key_expr: value_expr for targets in iterable <additional loops or if expressions>} can always be made compatible with Python < 2.7 by using: … Read more