[英]Comparing between an element in a list and a dictionary in python
#!/bin/python3
import sys
n=int(sys.stdin.readline())
dicti={}
for i in range(n):
str1=sys.stdin.readline()
key,value=str1.split(" ")
dicti[key]=value
string1=[]
while True:
check=sys.stdin.readline()
if check!="\n":
string1.append(check)
else:
break
for i in string1:
for key,value in dicti.items():
if i==key: <-- comparison fails!!
sys.stdout.write(i)
基本上,我將值(同一行的名稱和數字,以空格分隔)讀入字典。 然后我將查詢讀入列表。 現在我將列表中的元素與字典中的鍵進行比較,並打印該元素(如果存在)。 我不明白為什么比較失敗,即使值相同。 任何見解表示贊賞。
根據我的理解,這會做你想要的
n = int(input("Enter the number of key value pairs in dictionary."))
dicti = {}
for i in range(n):
key, value = input("Enter the pair\t").split()
dicti[key] = value
string1 = []
while True:
check = input()
if check != "": # takes input till empty string
string1.append(check)
else:
break
l = []
for i in string1:
for key, value in dicti.items():
if i == key:
l.append(i)
print("For following values i equals key :", *l)
它提供以下輸出:
Enter the number of key value pairs in dictionary.3
Enter the pair 1 2
Enter the pair 2 3
Enter the pair 3 4
1
2
For following values i equals key : 1 2
Process finished with exit code 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.