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.
2 Answers 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}]
1 Comment
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"