dict = {46: [{'picker_name': 'Table_1', 'picker_id': 970}],
47: [{'picker_name': 'Table_7', 'picker_id': 994}, {'picker_name': 'Table_9', 'picker_id': 999}]}
i want to access the only picker_id of every key for answer of this quetion:- 46: 970, 47: 994, 999 i also try but i did not get right logic pls help me i am stuck from very long. i am newbie in python
these my logic:-
for key in dict:
for i in range(len(dict[key])):
for it in dict[key][i].values():
print(it)
i got the output of this is:-
Table_1
970
Table_7
994
Table_9
999
Two iterations will work here, you do not need to use range()
d = {46: [{'picker_name': 'Table_1', 'picker_id': 970}],
47: [{'picker_name': 'Table_7', 'picker_id': 994}, {'picker_name': 'Table_9', 'picker_id': 999}]}
for k, v in d.items():
for d in v:
print(k, d['picker_id'])
Output
46 970
47 994
47 999
Another solution using map
d = {46: [{'picker_name': 'Table_1', 'picker_id': 970}],
47: [{'picker_name': 'Table_7', 'picker_id': 994}, {'picker_name': 'Table_9', 'picker_id': 999}]}
res = {}
for key, pickers in d.items():
res[key] = list(map(lambda picker: picker['picker_id'], pickers))
print(res) #{46: [970], 47: [994, 999]}
I will try my best to clear the concept. First of all, loop in the dictionary using.items() returns a dictionary view object that provides a dynamic view of dictionary elements as a list of key-value pairs.
dict_items([(46, [{'picker_name': 'Table_1', 'picker_id': 970}]), (47, [{'picker_name': 'Table_7', 'picker_id': 994}, {'picker_name': 'Table_9', 'picker_id': 999}])])
In the loop below the key will hold the first value ie 46 and the value will hold the second item which is the list.
Now run the loop in the value list. The elements represent each element in the list. Since the each element of the list is a dictionary, you can access the value of the 'picked_id' using the key 'picked_id'.
for key,value in dict.items():
for elements in value:
print(key,elements['picker_id'])
I hope this helps. All The Best! Good Luck on learning Python.
OutPut:
46 970
47 994
47 999
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.