Reputation: 2780
I am new to python and I have struggling for a while in trying to convert the following list into a dictionary.
lst = ['AB_MK1230', 'MK12303', 86.17, 'AB_MK1230', 'MK12302', 89.99,
'AB_MK1230', 'MK12301', 93.82, 'AB_MK1230', 'MK12301', 94.81, 'AB_MK1230',
'MK12303', 87.5, 'AB_MK1230', 'MK12302', 94.67, 'AB_MK1230', 'MK12302', 90.32,
'AB_MK1230', 'MK12303', 89.26, 'AB_MK1230', 'MK12301', 91.75,'AB_MK1230',
'MK12302', 88.54, 'AB_MK1230', 'MK12303', 92.5,'AB_MK1230', 'MK12301', 93.49,
'AB_MK1230', 'MK12301', 86.47,'AB_MK1230', 'MK12302', 84.79,'AB_MK1230',
'MK12303', 86.57,'AB_MK1230', 'MK12301', 79.24,'AB_MK1230', 'MK12302', 80.34,
'AB_MK1230', 'MK12303', 76.88]
AB_MK1230 is the parent sector and MK12303, MK12301 and MK12302 are the child sectors. My output is to have a dictionary with the key of each child sector and the parent sector and float values as the values for that key, something like the following.
dict = {MK12301: AB_MK1230, 93.82, 94.81, 91.75, 93.49, 86.47, 79.24
MK12302: AB_MK1230, 89.99, 94.67, 90.32, 88.54, 84.79, 80.34
MK12303: AB_MK1230, 86.17, 87.50, 89.26, 92.50, 86.57, 76.88 }
I have read some documentation from https://docs.python.org/3/tutorial/datastructures.html?highlight=dictionaries but I still can't figure out the solution.
How can I achieve this?
Upvotes: 0
Views: 63
Reputation: 16475
We iterate over the list, unpacking three items at a time in (parent, child, value)
-order. Using (parent, child)
as a key into a dictionary we then add the value into a set
.
import itertools
import collections
lst = ['AB_MK1230', 'MK12303', 86.17, 'AB_MK1230', 'MK12302', 89.99,
'AB_MK1230', 'MK12301', 93.82, 'AB_MK1230', 'MK12301', 94.81, 'AB_MK1230',
'MK12303', 87.5, 'AB_MK1230', 'MK12302', 94.67, 'AB_MK1230', 'MK12302', 90.32,
'AB_MK1230', 'MK12303', 89.26, 'AB_MK1230', 'MK12301', 91.75,'AB_MK1230',
'MK12302', 88.54, 'AB_MK1230', 'MK12303', 92.5,'AB_MK1230', 'MK12301', 93.49,
'AB_MK1230', 'MK12301', 86.47,'AB_MK1230', 'MK12302', 84.79,'AB_MK1230',
'MK12303', 86.57,'AB_MK1230', 'MK12301', 79.24,'AB_MK1230', 'MK12302', 80.34,
'AB_MK1230', 'MK12303', 76.88]
d = collections.defaultdict(set)
for parent, child, value in itertools.zip_longest(*[iter(lst)]*3, fillvalue=None):
d[(parent, child)].add(value)
d is now a dictionary like
defaultdict(set,
{('AB_MK1230', 'MK12301'): {79.24,
86.47,
91.75,
93.49,
93.82,
94.81},
('AB_MK1230', 'MK12302'): {80.34,
84.79,
88.54,
89.99,
90.32,
94.67},
('AB_MK1230', 'MK12303'): {76.88,
86.17,
86.57,
87.5,
89.26,
92.5}})
It's not entirely clear how your final data structure is supposed to look like. If you only want parent
as the top-level key, you can use a nested defaultdict
...
Upvotes: 2