1

I'm new to python. Please anyone help me to understand this statement of python. How it will work ?

  {x: {y: 0. for y in myClass.features} for x in myClass.items}
star123
  • 323
  • 2
  • 3
  • 9
  • Can you please post some code preceding this line of code – Agile_Eagle Jul 21 '18 at 12:05
  • It's not a for-loop, but a (nested) dict comprehension. See e.g.: https://www.python.org/dev/peps/pep-0274/ or https://stackoverflow.com/questions/14507591/python-dictionary-comprehension – user2390182 Jul 21 '18 at 12:09

2 Answers2

2

Basically what it do is to create a nested dictionary with all values equal to 0.0

class myClassrino:
    def __init__(self):
        self.features=[1,2,3,4,5]
        self.items=[3,4,5,6]

myClass=myClassrino()
output={x: {y: 0. for y in myClass.features} for x in myClass.items}
print(output)

Output is:

{3: {1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0}, 4: {1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0}, 5: {1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0}, 6: {1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0}}

Feel free to post anything you are still unclear..

Marcus.Aurelianus
  • 1,520
  • 10
  • 22
0

Just give it a try.

{x: {y: 0. for y in [1,2,3]} for x in ['a','b','c']}

=

{'a': {1: 0.0, 2: 0.0, 3: 0.0}, 'b': {1: 0.0, 2: 0.0, 3: 0.0}, 'c': {1: 0.0, 2: 0.0, 3: 0.0}}

Then ones can have some feeling about it from the output.


To be easier, you can decompose it:

{y: 0. for y in [1,2,3]}

=

{1: 0.0, 2: 0.0, 3: 0.0}

after substitution, we have

{x: {1: 0.0, 2: 0.0, 3: 0.0} for x in ['a','b','c']}

final answer =

{'a': {1: 0.0, 2: 0.0, 3: 0.0}, 'b': {1: 0.0, 2: 0.0, 3: 0.0}, 'c': {1: 0.0, 2: 0.0, 3: 0.0}}

Now you only need to replace

[1,2,3] and ['a','b','c']

to

myClass.features and myClass.items

Both are implicitly declared by defining them.


Sorry for my poor expression.

fmnijk
  • 411
  • 5
  • 12