ciskgo
ciskgo

Reputation: 23

Changing only one value of a key in a dictionary that has multiple values

I have a key with multiple values assigned. I would like to ask the user for input (new_population), and replace the old value (current_population) within the key. I would like the other value within the key (num) to remain unaffected.

current_population = 5 
num = 3
dict = {}
dict["key"] = [current_population, num]

new_population = input("What is the new population?")

Say (for example sake), the value of new_population is 10. My goal is a final output of:

{'key': [10, 3]}

How would I go about doing this?

Upvotes: 2

Views: 917

Answers (2)

Ben Schmidt
Ben Schmidt

Reputation: 401

To be clear, what you actually have is a dictionary where each element is a list. It is not possible to have multiple elements with the same key, since that would create undefined behaviour (which element would be returned by a lookup?). If you do

current_population = 5 
num = 3
mydict = {}
mydict["key"] = [current_population, num]
elem = mydict["key"]
print elem

you will see that elem is actually the list [5,3]. So to get or set either value, you need to index into the list you get from indexing into the dictionary.

mydict["key"][0] = new_population

(like in the accepted answer).

If you don't want to keep track of which index is population and which is num, you could make a dictionary of dictionaries instead:

mydict = {}
mydict["key"] = {"pop": current_population, "num", num}
mydict["key"]["pop"] = new_population

Upvotes: 1

Ned Batchelder
Ned Batchelder

Reputation: 375594

dict["key"][0] = new_population

Upvotes: 0

Related Questions