Iteration execution within the dict?

Can’t an execution be allowed within a dict initialization?

for i in some:
  dictVar = {
      'a': i['a'],
      'b': i['b'],
      'c': i['c'],
      for j in i['d']:
          j['e']: j['f']

Hello, @maathmaath, and welcome to Python Software Foundation Discourse!

See 5.5. Dictionaries in the 5. Data Structures documentation.

That section includes this example of a dict comprehension:

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}


You can also create nested dict comprehensions.

For clarification, would some, in your example, be an existing dictionary? Perhaps you could initialize that dictionary in your example, and specify what items would exist in the final resulting dictionary. That would help facilitate the discussion.

Yes, but the correct syntax is:

for i in some:
  dictVar = {
      'a': i['a'],
      'b': i['b'],
      'c': i['c'],
      **{j['e']: j['f'] for j in i['d']}

You’re conflating a dict literal with a dict comprehension. The following is valid:

    "k1": 1,
    "k2": 2,
    **{f"k{i}": i for i in range(3, 6)},

The intended outcome of the code in the original post is unclear to me.

However we can answer the original question, which is:

An answer to that question is that a dict comprehension is one example of how execution can indeed be used within a dict initialization.

The example code in the original post begins as follows:

A loop with such a header would repeatedly overwrite the value of the dictVar variable. But, perhaps the intention was instead to initialize and then build upon dictVar within each iteration.

If the aim of this discussion is to develop a new, currently nonexistent, mechanism for enabling execution within a dict initialization, a different syntax would need to be developed. We should then ask whether there is any compelling need for such an innovation.