Search code examples
pythonpandasstructure

I don't know how to deal with this kind of structure


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.


Solution

  • 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:

    • Lists are indexed by a continuous integer progression always starting at 0. (if you sort the list in a different way, 0 will always point to the first item, 1 to the second... and -1 to the last)
    • Dictionaries can be indexed by any immutable like numbers or strings, but are not store in any particular order regarding the keys. (if you sort the dictionary you need to store it as a list to keep the order, as sorting will not affect the underlying data structure)