如何将多个值存储到字典中的同一个键? [重复]

时间:2021-09-27 07:32:16

This question already has an answer here:

这个问题在这里已有答案:

I have to take inputs from a user and assign it to a dictionary in Python.

我必须从用户那里获取输入并将其分配给Python中的字典。

Inputs:
5
2000 8
1000 9
5000 10
2000 9
1000 8

Explanation: 5 is the total number of inputs which the user will input. So this doesn't need to be stored in a dictionary.

说明:5是用户输入的输入总数。所以这不需要存储在字典中。

Other values like "2000 8" need to be stored in a dictionary. Here "2000" is the key and "8" is the value. when the same key has the same values ("2000 8" and "2000 9") the key with the lowest value will be returned as an output.

其他值如“2000 8”需要存储在字典中。这里“2000”是关键,“8”是值。当相同的键具有相同的值(“2000 8”和“2000 9”)时,具有最低值的键将作为输出返回。

I tried doing this:

我试过这样做:

mydict = {}
for totnum in range(0,int(input('Input the total number'))):
    a, b = input('Enter the key value pair').split()
    mydict[a] = [b]

print(mydict)

But this is wrong because in case of duplicate keys (say "2000 8" and "2000 9") it will always store the last input by the user.

但这是错误的,因为在重复键(例如“2000 8”和“2000 9”)的情况下,它将始终存储用户的最后一个输入。

How can I store multiple values to the same key in a dictionary?

如何将多个值存储到字典中的同一个键?

1 个解决方案

#1


0  

You may have to have a check for appending.

您可能需要检查是否附加。

mydict = {}
for totnum in range(0,int(input('Input the total number'))):
    a, b = input('Enter the key value pair').split()
    if a in mydict:
        mydict[a].append(b)
    else:
        mydict[a] = [b]

print(mydict)

#1


0  

You may have to have a check for appending.

您可能需要检查是否附加。

mydict = {}
for totnum in range(0,int(input('Input the total number'))):
    a, b = input('Enter the key value pair').split()
    if a in mydict:
        mydict[a].append(b)
    else:
        mydict[a] = [b]

print(mydict)