Find the length of values of nested dictionary . And create new dictionary of same but with the percent of length

Code done before

Here I am getting the data like this:

{'Parameter_1': {'2021-11-16': [319.56, 319.56, 319.56], '2021-11-17': [335.48, 335.48, 335.48], '2021-11-18': [355.45, 355.45, 355.45]}, 'Parameter_2': {'2021-11-16': [319.56, 319.56, 319.56], '2021-11-17': [335.48, 335.48, 335.48], '2021-11-18': [355.45, 355.45, 355.45]}}

Now I wish to find length of the values of this [319.56, 319.56, 319.56]. And then with the help of length I am counting the percentage of values are getting in one that single day. So here I does this:

data=dict()
    for parameter in parameters:
        for key, values in data_response.items():
             data[key]=dict()
             for key_, value_ in values.items():
                data[key].setdefault(key_[:10],[]).append(value_)

    raw_data = []
        for key, values in data.items():
            for key1, value in values.items():
                total_data_count = len(value)
                percentage_data = (total_data_count * 100)/1440
                available_data = str(percentage_data)[:5]
                raw_data.append(available_data)

Here in raw_data I am getting percentage of data like this

['31.94', '92.36', '93.12', '32.29', '92.56', '93.19']
    

Now the key date and this percentage values I wish to store in one dict

Expected Output:

{'Parameter_1': {'2021-11-16': 31.94 , '2021-11-17': 92.36, '2021-11-18': 93.12}, 'Parameter_2': {'2021-11-16': 32.29, '2021-11-17':92.56 , '2021-11-18': 93.19}}

1 answer

  • answered 2022-05-04 12:50 Tranbi

    There seem to be some inconsistencies in your question: expected values are floats but you append strings to your list, the percentage calculation doesn't really makes sense to me (only dependent on the list length thus always the same in your example) but it might with complete data. Also it's not clear what parameters is (parameter is never used)

    Nevertheless I think you're over-complicating the problem and a single nested loop might do what you need:

    data_response = {'Parameter_1': {'2021-11-16': [319.56, 319.56, 319.56], '2021-11-17': [335.48, 335.48, 335.48], '2021-11-18': [355.45, 355.45, 355.45]}, 'Parameter_2': {'2021-11-16': [319.56, 319.56, 319.56], '2021-11-17': [335.48, 335.48, 335.48], '2021-11-18': [355.45, 355.45, 355.45]}}
    
    data = dict()
    
    for key, values in data_response.items():
        data[key]=dict()
        for key1, value in values.items():
            data[key][key1] = round((len(value) * 100)/1440, 2)
    
    print(data)
    

    Output:

    {'Parameter_1': {'2021-11-16': 0.21, '2021-11-17': 0.21, '2021-11-18': 0.21}, 'Parameter_2': {'2021-11-16': 0.21, '2021-11-17': 0.21, '2021-11-18': 0.21}}
    

    Is this what you are looking for?

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum