0

I have a dictionary which I have called categories = {category1:weight,category2:weight} where category1,2 are strings containing the name of my categories and weight is an float between 0 and 1. Within a function, I wish to add the category names as variables to the local namespace using

for category in categories:
    locals().update(category=0)

So that I may use them later on to sum over. I can't create these beforehand as I have no way of predetermining how many categories will need to be created. However, when I run this I find that my local namespace looks exactly as it did before I ran the code with the addition of 'category':0 so I am not sure what's going on. My full output is

>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'd': {'category1': 0.5, 'category2': 0.2}}
>>> for key in d:
...     locals().update(key=0)
... 
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'd': {'category1': 0.5, 'category2': 0.2}, 'key': 0}

My best guess is that when I use the assignment operator = python is ignoring the keyword I extracted from the dictionary.

If this is the case, what is the correct approach to achieving the desired result?

Update

This code is part of a program I'm writing to behave as a gradebook for my classes. I don't actually care about the values in the dictionary associated with each category. There is another dictionary called scores which contains assignment titles and their corresponding scores for each student. What I am trying to do is create variables which I can reference easily and then add integer scores to so I can calculate grades. This merely seemed to be the best way of achieving it given what I currently know.

Update

I have a bit of pseudocode to explain what I'm looking for here:

total = 0
    for category in categories:
        total += (category_weight*category)/category_total

    print(total)

Where each category is an integer variable with initial value 0. What I am trying to do is abuse the keys in the categories dictionary in such a way that I am able to use them to reference variables created within my calculate_score function.

Community
  • 1
  • 1
RhythmInk
  • 513
  • 1
  • 4
  • 18

1 Answers1

0

If all you want to do is to sum the values, why dont you go with something like this?

categories = {'a':0.12,'b':0.56}
s = sum(categories.values())
balderman
  • 22,927
  • 7
  • 34
  • 52