I am trying to convert a list of tuple to a list of dictionary with a data that looks like this:
data =[
('base-certificate', 60, 3, 2022),
('case-certificate', 1, 3, 2022),
('standard-certificate', 7, 3, 2022),
('base-certificate', 50, 4, 2022),
('case-certificate', 80, 4, 2022),
('standard-certificate', 10, 4, 2022)
]
The last two numbers are dates representing month and year, this means that there can also be data for April(4), May(5), etc. and it would be unique. so to create a date object in javascript these two numbers are needed preferably in a list [3, 2022].
I would like an output that looks like this:
[
{x:[3, 2022], base: 60, case:1, standard: 7},
{x:[4, 2022], base: 50, case:80, standard: 10}
]
I tried using the defaultdict from the collection library:
from collections import defaultdict
data=defaultdict(dict)
for a, b, c, d in se:
if "x" not in data[c, d]:
data[c, d]['x'] = [c,d]
data[c, d][a] = b
print(data)
The result of the code was:
defaultdict(<class 'dict'>, {(3, 2022): {'x': [3, 2022], 'base-certificate': 60, 'case-certificate': 1, 'standard-certificate': 7}, (4, 2022): {'x': [4, 2022], 'base-certificate': 50, 'case-certificate': 80, 'standard-certificate': 10}})
it was close but am missing something. Please what is the best approach in this case? and what am I am doing wrong, Thank you for your kind response.
CodePudding user response:
Here's a possible solution using itertools.groupby
.
If the dates are sorted you can use groupby
directly on the data, if not, you should sort by date first.
from itertools import groupby
result = []
for key, group in groupby(data, lambda x: (x[2], x[3])):
r = {'x': key}
for a, b, _, _ in group:
r[a.partition('-')[0]] = b
result.append(r)
print(result)
Output:
[{'x': (3, 2022), 'base': 60, 'case': 1, 'standard': 7}, {'x': (4, 2022), 'base': 50, 'case': 80, 'standard': 10}]
CodePudding user response:
Try:
data = [
("base-certificate", 60, 3, 2022),
("case-certificate", 1, 3, 2022),
("standard-certificate", 7, 3, 2022),
("base-certificate", 50, 4, 2022),
("case-certificate", 80, 4, 2022),
("standard-certificate", 10, 4, 2022),
]
out = {}
for name, val, month, year in data:
out.setdefault((month, year), {}).update(
{"x": [month, year], name.split("-")[0]: val}
)
print(list(out.values()))
Prints:
[
{"x": [3, 2022], "base": 60, "case": 1, "standard": 7},
{"x": [4, 2022], "base": 50, "case": 80, "standard": 10},
]