Issue
I have the following dictionnary:
my_list =_list = [
{"a": 1, "id": 1}, {"a": 2, "id": 1},
{"a": 3, "id": 2}, {"a": 4, "id": 2}
]
How can I get this output ("id.value": [values of "a"]
{"1": [1, 2], "2": [3, 4]}
I tried this :
dic={}
li=[]
for item in my_list:
li.append(item['a'])
dic["id"] = 1
dic["a"] = li
Solution
FIrst correct the commas in the dict.
my_dic = {}
for i in my_list:
if i["id"] in my_dic:
my_dic[i["id"]].append(i["a"])
else:
my_dic[i["id"]]=[i["a"]]
Answered By - omar magdi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.