Home > Mobile >  Changing the underlying variable's value in a dictionary of variables
Changing the underlying variable's value in a dictionary of variables

Time:11-17

How can I change the value of a variable using dictionary? Right now I have to check every key of the dictionary and then change the corresponding variable's value.

`

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

dictionary = {
    "dog": list1,
    "cat": list2,
    "mouse": list3
}

animal = input("Type dog, cat or mouse: ")
numbers_list = dictionary[animal]

# Adds 1 to all elements of the list
numbers_list = [x 1 for x in numbers_list]

# Is there an easier way to do this?
# Is there a way to change the value of the original list without
# using large amount of if-statements, since we know that
# dictionary[animal] is the list that we want to change?
# Using dictionary[animal] = numbers_list.copy(), obviously wont help because it
# only changes the list in the dictionary
if animal == "dog":
    list1 = numbers_list.copy()
if animal == "cat":
    list2 = numbers_list.copy()
if animal == "mouse":
    list3 = numbers_list.copy()
print(list1, list2, list3)

`

I've tried using dictionary[animal] = numbers_list.copy() but that just changes the value in the dictionary, but not the actual list. Those if-statements work, but if there is a large dictionary, it is quite a lot of work.

CodePudding user response:

You can replace the dict value with a new list on the fly -

dictionary[animal] = [i 1 for i in dictionary[animal]]

I would suggest to stop using the listx variables and use dict itself to maintain those lists and mappings.

dictionary = {
    "dog": [1, 2, 3],
    "cat": [4, 5, 6],
    "mouse": [7, 8, 9]
}

animal = "cat"
dictionary[animal] = [i 1 for i in dictionary[animal]]
print(dictionary[animal])

#instead of printing list1, list2, list3, print the key, values in the dict
for animal, listx in dictionary.items():
    print(animal, listx)

Output:

[5, 6, 7]
dog [1, 2, 3]
cat [5, 6, 7]
mouse [7, 8, 9]

CodePudding user response:

There's no need for separate lists. You can assign the lists directly as part of the dictionary definition.

animals = {
    "dog": [1, 2, 3],
    "cat": [4, 5, 6],
    "mouse": [7, 8, 9]
}

animal = input("Type dog, cat or mouse: ")

Once you know the animal name, you can iterate over the list directly and increment each number:

for i in range(len(animals[animal])):
    animals[animal][i]  = 1
  • Related