Bind list of dictionary by a common key?
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 1:
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"]]
Solution 2:
I'm not sure if this is too convoluted of an answer/if you were looking for a one-liner, but this is the approach I would take:
Create a unique list of ids:
my_list = [{"a": 1, "id": 1}, {"a": 2, "id": 1},{"a": 3, "id": 2}, {"a": 4, "id": 2} ]
unique_id = set([dictionary["id"] for dictionary in my_list])
Then create an empty dictionary, iterate through your ids, and then iterate through your list of dictionaries for every id and if that dictionary has the right id, append the "a" value to a temp list, and then set that to the empty dictionary:
bind = {}
for id in unique_id:
tmp = []
for dictionary in my_list:
if dictionary["id"] == id:
tmp.append(dictionary["a"])
bind[id] = tmp
This gave me the desired output:
>>> bind
{1: [1, 2], 2: [3, 4]}