Please tell me how to create a dictionary from the existing list:
my_list = [[['id_1', 'A', 10], ['id_1', 'C', 3], ['id_1', 'B', 2]],
[['id_2', 'E', 4], ['id_2', 'A', 3], ['id_2', 'D', 1]],
[['id_3', 'B', 3], ['id_3', 'C', 1]],
[['id_4', 'E', 10], ['id_4', 'A', 5], ['id_4', 'B', 4], ['id_4', 'F', 2]]]
I need to get a dictionary like this:
dictionary = {'A': [('id_1', 10 ), ('id_4', 5), ('id_2', 3)],
'B': [('id_4', 4), ('id_3', 3), ('id_1', 2)],
'C': [('id_1', 3), ('id_3', 1)],
'D': [('id_2', 1)],
'E': [('id_4', 10), ('id_2', 4)],
'F': [('id_4', 2)]
}
Thanks for the help!
CodePudding user response:
Start with a defaultdict
and append values from my_list
then sort.
from collections import defaultdict
my_list = [[['id_1', 'A', 10], ['id_1', 'C', 3], ['id_1', 'B', 2]],
[['id_2', 'E', 4], ['id_2', 'A', 3], ['id_2', 'D', 1]],
[['id_3', 'B', 3], ['id_3', 'C', 1]],
[['id_4', 'E', 10],['id_4', 'A', 5],['id_4', 'B', 4], ['id_4', 'F', 2]]]
d = defaultdict(list)
[d[i[1]].append((i[0],i[2])) for j in my_list for i in j]
dictionary = dict(sorted(d.items()))
CodePudding user response:
You can try this:
my_list = [[['id_1', 'A', 10], ['id_1', 'C', 3], ['id_1', 'B', 2]],
[['id_2', 'E', 4], ['id_2', 'A', 3], ['id_2', 'D', 1]],
[['id_3', 'B', 3], ['id_3', 'C', 1]],
[['id_4', 'E', 10], ['id_4', 'A', 5], ['id_4', 'B', 4], ['id_4', 'F', 2]]]
flattened = [item for sublist in my_list for item in sublist]
my_dict = {}
for _id, ltr, num in flattened:
if ltr in my_dict: # changed from my_dict.keys()
my_dict[ltr].append((_id, num))
else:
my_dict[ltr] = [(_id, num)]
sorted_dict = dict(sorted(my_dict.items()))
print(sorted_dict)
If you want to know, this is what flattened
, my_dict
and sorted_dict
look like:
flattened = [
['id_1', 'A', 10], ['id_1', 'C', 3], ['id_1', 'B', 2],
['id_2', 'E', 4], ['id_2', 'A', 3], ['id_2', 'D', 1],
['id_3', 'B', 3], ['id_3', 'C', 1], ['id_4', 'E', 10],
['id_4', 'A', 5], ['id_4', 'B', 4], ['id_4', 'F', 2]
]
my_dict = {
'A': [('id_1', 10), ('id_2', 3), ('id_4', 5)],
'C': [('id_1', 3), ('id_3', 1)],
'B': [('id_1', 2), ('id_3', 3), ('id_4', 4)],
'E': [('id_2', 4), ('id_4', 10)],
'D': [('id_2', 1)],
'F': [('id_4', 2)]
}
sorted_dict = {
'A': [('id_1', 10 ), ('id_4', 5), ('id_2', 3)],
'B': [('id_4', 4), ('id_3', 3), ('id_1', 2)],
'C': [('id_1', 3), ('id_3', 1)],
'D': [('id_2', 1)],
'E': [('id_4', 10), ('id_2', 4)],
'F': [('id_4', 2)]
}
CodePudding user response:
You can just use nested loops..
my_dict = {}
for i in my_list:
for j in i:
try:
my_dict[j[1]] = [(j[0], j[-1])]
except KeyError:
my_dict[j[1]] = [(j[0], j[-1])]
my_dict = dict(sorted(my_dict.items()))
my_dict
----------------------------------------------------
{'A': [('id_1', 10), ('id_2', 3), ('id_4', 5)],
'B': [('id_1', 2), ('id_3', 3), ('id_4', 4)],
'C': [('id_1', 3), ('id_3', 1)],
'D': [('id_2', 1)],
'E': [('id_2', 4), ('id_4', 10)],
'F': [('id_4', 2)]}
----------------------------------------------------