I have to structure data like this:
[NEW STRUCTURE]:
{name:[{base_name1:[{'date', date}, {c:s}], base_name2:[{'date', date}, {c:s}]}]}
I need to parse it from structure like:
[OLD_STRUCTURE]
{name: [{base: {calls: success}}]}
Where base is a string which contains base_name
and date
.
I have a sample code, but it doesn't work.
mp, op = {}, {}
print(b)
for name, base in summary.items():
for b in base:
pr = list(b.keys())[0]
pr_date = pr[len(pr) - 10:]
pr = pr[:-10]
if pr_date >= start_date:
mp.update({name: []})
mp[name].append({pr: []})
mp[name][pr].append({'date': pr_date}, {list(list(b.values())[0].keys())[0]: list(list(b.values())[0].values())[0]})
else:
print('1')
But it shows:
TypeError: list indices must be integers or slices, not str
I don't know where's the problem.
Hope you can help me.
The problem is in these two lines:
mp[name].append({pr: []})
mp[name][pr].append({'date': pr_date}, {list(list(b.values())[0].keys())[0]: list(list(b.values())[0].values())[0]})
First you set mp[name] to have two nested structures, a list containing a dictionary (pr is the index for the dictionary, the inner structure), yet you try to use pr to index the list instead of the dict.
Assuming your NEW_STRUCTURE is ... {'date': date} ... (a colon instead of a comma, so base_name1 points to a list of dictionaries). Try:
mp, op = {}, {}
for name, base in summary.items():
mp[name] = []
for b in base:
pr = list(b.keys())[0]
pr_date = pr[len(pr) - 10:]
if pr_date >= start_date:
mp[name].append({name:[{'date': pr_date}, b[pr]]})
else:
print('1')
And a little bit on indexing: