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}
2

2 Answers 2

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..

Sign up to request clarification or add additional context in comments.

3 Comments

thank you. y : 0 here : is equal to assignment operator or what ?
@y : 0 equal to d[y]=0, you can check it out here. docs.python.org/3/library/stdtypes.html#mapping-types-dict
Consider accept the answer by clicking the check on the left of question, it will remove the this from review queue, save other moderators time and distribute the points around.
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.

1 Comment

Thank you. You explained very well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.