简体   繁体   中英

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)

Basically, I read values(name and number on same line, separated by space) into dictionary. Then I read the queries into a list. Now I compare if the element in the list with the key in the dictionary and prints the element if present. I do not understand why the comparison fail,even when the value are same. Any insight is appreciated.

As per what i understood ,this will do what u want

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)

It gives the following output:

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

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