dict-comprehension

if-else in a dictionary comprehension [duplicate]

不羁的心 提交于 2020-05-01 20:48:17
问题 This question already has answers here : Ternary expression in dictionary comprehension (2 answers) Closed 3 years ago . Is it possible to use the else statement (and if yes, how?) in a dictcomp ? It is not possible to use else as part of the comprehension itself (see this) but at least in list and set comprehensions it is possible to use the conditional_expression (see this). An example for listcomp is here. My example code is: converters = {"id": int} rows = [{"id": "1", "name": "foo"}, {

Dict merge in a dict comprehension

柔情痞子 提交于 2019-12-03 15:27:52
问题 In python 3.5, we can merge dicts by using double-splat unpacking >>> d1 = {1: 'one', 2: 'two'} >>> d2 = {3: 'three'} >>> {**d1, **d2} {1: 'one', 2: 'two', 3: 'three'} Cool. It doesn't seem to generalise to dynamic use cases, though: >>> ds = [d1, d2] >>> {**d for d in ds} SyntaxError: dict unpacking cannot be used in dict comprehension Instead we have to do reduce(lambda x,y: {**x, **y}, ds, {}) , which seems a lot uglier. Why the "one obvious way to do it" is not allowed by the parser, when

Dict merge in a dict comprehension

自闭症网瘾萝莉.ら 提交于 2019-12-03 05:55:41
In python 3.5, we can merge dicts by using double-splat unpacking >>> d1 = {1: 'one', 2: 'two'} >>> d2 = {3: 'three'} >>> {**d1, **d2} {1: 'one', 2: 'two', 3: 'three'} Cool. It doesn't seem to generalise to dynamic use cases, though: >>> ds = [d1, d2] >>> {**d for d in ds} SyntaxError: dict unpacking cannot be used in dict comprehension Instead we have to do reduce(lambda x,y: {**x, **y}, ds, {}) , which seems a lot uglier. Why the "one obvious way to do it" is not allowed by the parser, when there doesn't seem to be any ambiguity in that expression? It's not exactly an answer to your question