0

Can someone help me rewrite this single line loop to a multiple lines for loop in python? I am trying to understand how it is formatted.

y = {element: r for element in variables(e)}
Kai
  • 15
  • 4
  • What do you need help with exactly? Create an empty dictionary and add one item in each iteration of the loop. – mkrieger1 Oct 30 '20 at 22:55
  • 1
    Dictionary comprehensions **are not single line for-loops**. Do not think of them as such. – juanpa.arrivillaga Oct 30 '20 at 22:57
  • @juanpa.arrivillaga If the Python designers didn't want people to think of them like that, they shouldn't have used such similar syntax. :) – Barmar Oct 30 '20 at 22:59
  • The title of the linked duplicate mentions list comprehensions, but the accepted answer includes dictionary comprehensions, and they are the same fundamental thing – juanpa.arrivillaga Oct 30 '20 at 22:59
  • @Barmar perhaps, but the language maintainers are big on re-using keywords whenever possible. – juanpa.arrivillaga Oct 30 '20 at 23:01
  • [Python List Comprehensions: Explained Visually](https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/) – Timus Oct 30 '20 at 23:04
  • A better target: [What is this python expression containing curly braces and a for in loop?](https://stackoverflow.com/q/31846592/7851470) – Georgy Oct 30 '20 at 23:05

2 Answers2

2

The dictionary comprehension is equivalent to this loop:

y = {}
for element in variables(e):
    y[element] = r
Barmar
  • 596,455
  • 48
  • 393
  • 495
0

This is called a dict comprehension in python.

This syntax builds a dictionary by taking each element in the list variables(e) and associating it with the value r.

Tordek
  • 10,075
  • 3
  • 31
  • 63