简体   繁体   中英

change global variable through dictionary (python)

Beginner question here. I'm trying to modify a global variable by a function using dictionary. Sample code here:

count = 0
sample = {'a' : [False, count, 20], 'b' : [False, count, 60]}

d = raw_input('give dict key: ')
    for each in sample:
        if each == d:
            sample[each][0] = True
        sample[each][1] += sample[each][2]

print('count ' + str(count))
print(sample) 
print('count ' + str(count))

The result is (no surprise):

give dict key: b
count 0
{'a': [False, 0, 20], 'b': [True, 60, 60]}
count 0

I understand the result, but I'd like to know if there's any way to access and change the global variable, so that count in last line would give 60 not 0 . (Preferably with simple methods, OOP is out of my reach at the moment).

#

EDIT: Thank you for the answers! I wasn't precise enough and proposed solutions will not work in my case. The statement above is a part of a bigger function and there's more variables also, let's try to redefine it:

countOne = 0
countTwo = 0

sample = {'a' : [False, countOne, 20, 'mouse'], 'b' : [False, countTwo, 60, 'cat']}



def someFunction():
    global countOne, countTwo
    while something:
        if somethingElse:
            if anotherThing:
                d = raw_input('give dict key: ')
                for each in sample:
                    if each == d:
                        sample[each][0] = True
                        sample[each][1] += sample[each][2]

print('count ' + str(count))
print(sample) 
print('count ' + str(count))

I'm sorry for confusion, haven't thought that shortening it, would allow other methods to be applicable.

For the first answer, it wouldn't work, because in my dictionary I have quite a lot of global variables (more than those two above) and according to the raw_input the specific variable should be accessed and modified.

For the second answer, it wouldn't work as it's not local anymore.

Ok, an assumption. I'm assuming that you don't know ahead of time which variable you're going to be modifying.

If that's accurate, the following will do what you want:

count = 0
sample = {'a' : [False, 'count', 20], 'b' : [False, 'count', 60]}

d = input('give dict key: ')
print('count ' + str(count))
for each in sample:
    if each == d:
        sample[each][0] = True
        locals()[sample[each][1]] += sample[each][2]


print(sample) 
print('count ' + str(count))

Yields:

give dict key: b
count 0
{'a': [False, 'count', 20], 'b': [True, 'count', 60]}
count 60

Note that I changed the second entry in each list to a string, so it's not interpreted at the point of the dictionary creation.

locals() will return the list of the local symbol table. Note that in this context, count is a local variable, not a global variable. You're just at the highest scope so it's a distinction without a difference. Once you have the symbol table you can assign to it like any list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM