-4

I have some vars and its values:

var1, var2, var3, var4 = 9, 8, 7, 6

I have dict:

map = {
    1: 'var1', 
    2: 'var2', 
    3: 'var3', 
    4: 'var4', 
}

I have some calculations and get number:

key = 2  # 1/3/4

Can I somehow change var (ex. var2) by addressing to it something like map[key] += 10 so print(var2) shows 18?


Ok. Real code:

deleted, invalid, no_item, no_game, generic, no_dnvt, vt_null, unknown = 0,0,0,0,0,0,0,0
# some code ...
if result < 0:
    deleted += 1
    if result == -1:    # invalid file (no root)
        invalid += 1
    elif result == -2:  # invalid file (no GameObjects node)
        invalid += 1
    elif result == -3:  # not an "Item" type
        no_item += 1
    elif result == -4:  # attribute "HasGameplayValue" is False
        no_game += 1
    elif result == -5:  # Stats points to a generic/immutable object
        generic += 1
    elif result == -6:  # no DisplayName or VisualTemplate
        no_dnvt += 1
    elif result == -7:  # VisualTemplate with no value
        vt_null += 1
    elif result == -8:  # DisplayName with unknown handle
        unknown += 1
    # some code ...
    continue

So we have exactly same action (+= 1) but with different vars. I want to make this code shorter and clearer. And w/o "match case" or bunch of ifs.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
ZoolooS
  • 1
  • 3
  • 3
    Why the indirection through variable names at all?! Just assign the values directly to the dict…!? – deceze Aug 28 '23 at 03:06
  • The variables already exist. I need to change them, not get rid of them. – ZoolooS Aug 28 '23 at 03:27
  • 2
    Just use a dict or object attributes instead of individual variables. You _can_ use [`globals`](https://stackoverflow.com/a/1373201/476), but… ugh…! – deceze Aug 28 '23 at 03:27
  • I can't understand how it can do my code shorter. I calculate the `result` and then, depending on its value, I need to change another variable, which is later used by other code. – ZoolooS Aug 28 '23 at 03:37
  • 3
    Again: see https://stackoverflow.com/q/1373164/476 for various ways to use variable variables, i.e. looking up and setting variables by name. The usual answer is: don't, use a dict instead. But if you have to, that other question contains all the different suggestions for working with variables by name. – deceze Aug 28 '23 at 03:58

0 Answers0