2

I just started with python , and now I am trying to understand dictionary comprehension , but I don't get the behaviour of the following code :

 data = [
 {'id': 12, 'data': '01'},
 {'id': 10, 'data': '05'},
 {'id': 11, 'data': '07'},
 ]
 { d['id']:d for d in data }.values()

Output :

dict_values([{'id': 12, 'data': '01'}, {'id': 10, 'data': '05'}, {'id': 11, 'data': '07'}])

please explain the output for the mentioned code . Why it is printing 2nd key value pair of each dictionary of data i.e. 'data':'01' and so on.

asked Mar 26, 2017 at 17:35

2 Answers 2

2

You have create list of dict

data = [ {'id': 12, 'data': '01'}, {'id': 10, 'data': '05'}, {'id': 11, 'data': '07'}, ]

If we split first statement then we will get following result.

{ d['id']:d for d in data }

{10: {'data': '05', 'id': 10}, 11: {'data': '07', 'id': 11}, 12: {'data': '01', 'id': 12}}

d is you first dict & you are creating new dict with d[id]

d['id']:d -> 10: {'data': '05', 'id': 10}

values() : This method returns a list of all the values available in a given dictionary.

In your example 3 dict are values.

That's why you are getting result like.

[{'data': '05', 'id': 10}, {'data': '07', 'id': 11}, {'data': '01', 'id': 12}]

answered Mar 26, 2017 at 17:45
Sign up to request clarification or add additional context in comments.

1 Comment

You should use the code formatting for the code parts.
2

data is an array that contains 3 dictionnaries, each one having 2 keys : "id" and "data".

What you are asking python is :

{ d['id']:d for d in data }

"Build me a dictionnary that contains 1 pair key/value for each element of my data array. Each key should be the "id" value of this element, and each value should be the element of d itself"

What you probably want to do is :

In [6]: c={ d['id']:d["data"] for d in data}
In [7]: c
Out[7]: {10: '05', 11: '07', 12: '01'

"Build me a dictionnary that contains 1 pair key/value for each element of my data array. Each key should be the "id" value of this element, and each value should be the "data" value of of this element"

answered Mar 26, 2017 at 17:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.