Creates a new dictionary consisting of another dictionary key and two variables

Question:

I would like to create a dictionary consisting of key (key of dictionary x), Calc_1 and Calc_2

As you can see, there is already an older dictionary called x (x is not important for the purpose of the question). Dictionary x generates Calc_1 and Calc_2 for each of its keys. This works correctly.

Now i would like to group the variables Calc_1 and Calc_2 and each corresponding key into a new dictionary. So I would like to create a newdict dictionary that contains
key, (key of dictionary x) and Calc_1 and Calc_2. How can i?

newdict = {}

for key, value in x.items():
    Calc_1= sum(value[4]) / len(value[4])
    Calc_2 = (Calc_1 *100) / 2
  
    if Calc_1 > 0.5:
        if key not in newdict:
            newdict[key] = list([key, Calc_1, Calc_2])
            newdict[key][Calc_1] = [newdict[key][Calc_1]]
        else:
            newdict[key][Calc_1].append(Calc_2)

print(newdict)

I get the error TypeError: list indices must be integers or slices, not float, but surely the problem will be another

Asked By: Takao貴男

||

Answers:

Calc_1 is the average that was calculated earlier, so it’s a float, which can’t be used as a list index.

But there’s no reason why you should be indexing newdict[key] in the first place. It’s just a list of 3 elements that you created on the previous line, why would you be indexing it dynamically?

Just create the list in the new dictionary. There’s no need for the if check since keys are unique.

        newdict[key] = [key, Calc_1, Calc_2]
Answered By: Barmar