How do I compare the keys of a hash to a user input?

Asked

Viewed 137 times

5

Filing cabinet:

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 keys of the rexh hash with the user input to get the right surfer 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 of the respective surfer.

2 answers

6

You can use the library csv to do the Parsing in the CSV file and look for some value of a given field.

In your case the value to be researched would be the ID provided 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!")

Input ID

107

Exit

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

Source.

4


Although you already have a good answer, it is worth noting that your code already works and you no need for csv library.

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

I mean, do it like this:

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])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.