[英]What is wrong with the program I have written in python?
The question description is Write a program to get the input of key and value of the element in dictionary.问题描述是编写一个程序来获取字典中元素的键和值的输入。
Display the key-value pair in the python dictionary format and find the length of the dictionary.以 python 字典格式显示键值对,求字典长度。
Test Case 1:测试用例 1:
INPUT输入
3
23
33
43
32
33
34
OUTPUT OUTPUT
The dictionary is
{23: 32, 33: 33, 43: 34}
Length of dictionary is
3
My code is:我的代码是:
n = int(input())
di = dict()
for i in range(0, n):
a = int(input())
b = int(input())
di[a] = b
print("The dictionary is")
print(di)
print("Length of dictionary is")
print(len(di))
The output I am getting for the same input given above is:对于上面给出的相同输入,我得到的 output 是:
The dictionary is
{23: 33, 43: 32, 33: 34}
Length of dictionary is
3
What is my mistake?我的错误是什么?
It looks like the input provided is in the following order: i) size of the dictionary ii) the keys iii) the values看起来提供的输入按以下顺序排列:i)字典的大小 ii)键 iii)值
You seem to read it as key, value, key value...您似乎将其解读为键、值、键值...
The input provided is in the following order:提供的输入按以下顺序排列:
So your code should look more like this:所以你的代码应该看起来更像这样:
# collecting length
n=int(input())
# creating lists for keys and values
keys_list = []
values_list = []
# collecting keys
for i in range(0,n):
a=int(input())
keys_list.append(a)
# collecting values
for i in range(0,n):
a=int(input())
values_list.append(a)
# creating dictionnary
di = dict(zip(keys_list, values_list))
# printing result
print("The dictionary is")
print(di)
print("Length of dictionary is")
print(len(di))
Like this, you're first collecting all the keys and putting them in a list, then you're collecting all the values and putting them in a list.像这样,您首先收集所有键并将它们放入一个列表中,然后您将收集所有值并将它们放入一个列表中。
Finally, you're creating your dictionnary from these two lists.最后,您将从这两个列表中创建您的字典。
Maybe simply this:也许只是这样:
n = int(input('Input len of dict: '))
j = 0
l = []
while j != n * 2:
l.append(input('input num: '))
j += 1
di = {int(x): int(x[::-1]) for x in l[:3] if x[::-1] in l}
print(f"The dictionary is {di}\nLength of dictionary is {len(di)}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.