notguud
notguud

Reputation: 3

Changing a list value while said value is assigned to a variable

To avoid a long if / else string, I wanted to see if I could use a for-loop to increase a value in the userstats list by putting the value's position into a dict with its corresponding stat. A test list, userstats = [40, 40, 40, 40, 40, 40, 40] should be [50, 50, 40, 40, 40, 40, 40] when "Strength Intelligence" is inputted.

userstats = [40, 40, 40, 40, 40, 40, 40]

statdict = {"Strength":userstats[0], "Intelligence":userstats[1], "Willpower":userstats[2], "Agility":userstats[3], "Speed":userstats[4], "Endurance":userstats[5], "Personality":userstats[6]}
usfavstat = input("Enter your favored stats, seperated by one space. : ").title().split(" ")
for key, entry in statdict.items():
  if key in usfavstat:
    entry += 10

# Test input: Strength Intelligence
# Desired outcome: userstats = [50, 50, 40, 40, 40, 40, 40]
# Actual outcome: userstats = [40, 40, 40, 40, 40, 40, 40]

However, this did not work. I am looking for a way to change the values of a list using said values position attached to entry in a for loop. I'm pretty sure that, as constructed, entry doesn't represent the position, but rather its value. I do hope there is a way of doing this.

Upvotes: 0

Views: 46

Answers (3)

iGian
iGian

Reputation: 11183

Not having a full picture of the problem, I can only suggest this solution which I consider cleaner (using zip) and more user friendly (avoid asking the user to type the dict keys):

userstats = [40, 40, 40, 40, 40, 40, 40]
typestats = ["Strength", "Intelligence", "Willpower", "Agility", "Speed", "Endurance", "Personality"]

statdict = dict(zip(typestats, userstats))

for typestat in typestats:
  val = input(f'Will update {typestat} stat? (Y/N):').capitalize()
  if val == 'Y':
    statdict[typestat] += 10

print(statdict)
print(userstats)

This is not updating the userstats list

Upvotes: 0

ObjectJosh
ObjectJosh

Reputation: 641

Here you go:

userstats = [40, 40, 40, 40, 40, 40, 40]

statdict = {"Strength":userstats[0], "Intelligence":userstats[1], "Willpower":userstats[2], "Agility":userstats[3], "Speed":userstats[4], "Endurance":userstats[5], "Personality":userstats[6]}
usfavstat = input("Enter your favored stats, seperated by one space. : ").title().split(" ")

for key, entry in statdict.items():
    if key in usfavstat:
        statdict[key] = entry + 10
print(statdict)

Upvotes: 0

ThePyGuy
ThePyGuy

Reputation: 18406

Where this entry += 10 is being assigned to the dictionary?

You need to store this new value back to the dictionary.

for key, entry in statdict.items():
    if key in usfavstat:
        entry += 10
        statdict[key] = entry

Upvotes: 2

Related Questions