Reputation: 29
I am trying to attempt a python question regarding queue.
I am wondering why the dictionary is only printing values from the 2nd key and value pair. Why is the first pair not being printed?
Here are the relevant codes:
n = int(input("Enter total number of people queueing."))
dict = {}
for i in range(n):
inputKey = input("Select your choice of queue. Please enter 'M' for main queue or 'T' for team queue.\n")
inputValue = input("Enter your name: ")
dict[inputKey] = inputValue
print(dict)
Sample Input:
3
M
Bella
M
Swan
T
Cullen
Actual Output:
{'M': 'Swan', 'T': 'Cullen'}
Expected Output:
{'M': 'Bella', 'M': 'Swan', 'T': 'Cullen'}
Upvotes: 1
Views: 85
Reputation: 444
As Sayse explains, you are overwriting the values.
If you would like to append new entries you could use the following:
n = int(input("Enter total number of people queueing."))
dictionary = {}
for i in range(n):
inputKey = input("Select your choice of queue. Please enter 'M' for main queue or 'T' for team queue.\n")
inputValue = input("Enter your name: ")
if inputKey in dictionary:
dictionary[inputKey].append(inputValue)
else:
dictionary[inputKey] = [inputValue]
print(dictionary)
It would return the following output:
{'M': ['Bella', 'Swan'], 'T': ['Cullen']}
I would also avoid naming dictionaries dict
.
As keys need to be unique in a dict
, your expected output of {'M': 'Bella', 'M': 'Swan', 'T': 'Cullen'}
is not possible.
If you were a dict
and someone asked you to return the value for the key M
, what value would you return, Bella
or Swan
?
Upvotes: 1