简体   繁体   中英

Dictionary only printing from 2nd keys&values onwards?

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'}

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 ?

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