How can I compare the keys of a hash with a user input?

4

File:

101;Johnny 'wave-boy' Jones;USA;8.32;Fish;21
102;Juan Martino;Spain;9.01;Gun;36
103;Joseph 'smitty' Smyth;USA;8.85;Cruizer;18
104;Stacey O'Neill;Ireland;8.91;Malibu;22
105;Aideen 'board babe' Wu;Japan;8.65;Fish;24
106;Zack 'bonnie-lad' MacFadden;Scotland;7.82;Thruster;26
107;Aaron Valentino;Italy;8.98;Gun;19

Code:

arquivo = open("surfing_data.csv")
rexh = {}
for linha in arquivo:
    (ID, nome, pais, média, prancha, idade) = linha.split(";")
    rexh[ID] = nome,pais,média,prancha,idade
escolha = int(input("qual o id do surfista desejado : "))

How can I compare the hash 'rexh' keys with the user input to get the 'surfer's id'?

My idea is to compare the IDs (the numbers 101 ... 107) with the user input to select and show the user the information (the hash values) for him from the respective surfer.

    
asked by anonymous 28.01.2017 / 03:41

2 answers

3

Although you already have a good answer, it's worth noting that your code already works and you do not need the csv library.

Your rexh dictionary is already being created with surfers data. To access one of them, simply use the ID given by the user as the key: rexh[escolha] . But you should not convert the variable escolha to integer, since you do not do this conversion when you add the variable ID to rexh .

That is, do so:

arquivo = open("surfing_data.csv")
rexh = {}
for linha in arquivo:
    (ID, nome, pais, média, prancha, idade) = linha.split(";")
    rexh[ID] = nome,pais,média,prancha,idade
escolha = input("qual o id do surfista desejado : ") # <== Sem conversação do ID para inteiro

print(rexh[escolha])

Or so:

arquivo = open("surfing_data.csv")
rexh = {}
for linha in arquivo:
    (ID, nome, pais, média, prancha, idade) = linha.split(";")
    rexh[int(ID)] = nome,pais,média,prancha,idade # <== Com conversão do ID para inteiro aqui
escolha = int(input("qual o id do surfista desejado : ")) # <== E aqui também

print(rexh[escolha])
    
28.01.2017 / 13:21
5

You can use the csv library to # in the CSV file and search for some value in a given field.

>

In your case, the value to be searched would be ID supplied by the user, see below an example:

import csv

id = raw_input("Informe o ID: ")
resultado = ""

with open("execsv.csv", 'rb') as f:
    reader = csv.reader(f, delimiter=';')
    for registro in reader:
        if id == registro[0]:
            resultado = registro

if resultado:
    print (resultado)
else:
    print("Nada encontrado!")

ID Entry

  

107

Output

  

['107', 'Aaron Valentino', 'Italy', '8.98', 'Gun', '19']

Font .

    
28.01.2017 / 04:17