我有一个.txt文件,其中包含以下几行:
23;Pablo;SanJose
45;Rose;Makati
我有这个程序:
file = open("C:/Users/renato/Desktop/HTML Files/myfile2.txt")
def query(id):
for line in file:
table = {}
(table["ID"],table["name"],table["city"]) = line.split(";")
if id == int(table["ID"]):
file.close()
return table
else:
file.close()
return {}
id = int(input("Enter the ID of the user: "))
table2 = query(id)
print("ID: "+table2["ID"])
print("Name: "+table2["name"])
print("City: "+table2["city"])
所以正在发生的事情(据我所知)是:
文件已打开
创建一个名为table
的哈希,并将该文件的每一行拆分为3个键/值。
如果用户输入的id
与密钥ID
的值匹配,则关闭该文件
并返回整个哈希。
然后,我在table2
哈希上分配table
值,并且我正在尝试打印其中的值。
当我运行时,我得到以下内容:
Traceback (most recent call last):
File "C:/Users/renato/Desktop/HTML Files/Python/hash2.py", line 17, in <module>
print("ID: "+table2["ID"])
KeyError: 'ID'
似乎无法识别ID
var上的键table2
。我还尝试在执行函数之前将table2
声明为table2 = {}
,但它会继续显示错误消息。
如何将返回的哈希值分配给变量,以便我可以使用keys
打印它们?
答案 0 :(得分:10)
正在发生的事情是,您在文件的第一行与您要查找的ID不匹配后立即返回。你必须这样做:
def query(id):
for line in file:
table = {}
(table["ID"],table["name"],table["city"]) = line.split(";")
if id == int(table["ID"]):
file.close()
return table
# ID not found; close file and return empty dict
file.close()
return {}
答案 1 :(得分:1)
def query(id):
for line in file:
table = line.split(";")
if id == int(table[0]):
yield table
id = int(input("Enter the ID of the user: "))
for id_, name, city in query(id):
print("ID: " + id_)
print("Name: " + name)
print("City: " + city)
file.close()
使用收益..
答案 2 :(得分:0)
我按照下面代码所示的方法返回字典。创建一个类并声明字典为全局字典,并创建一个函数以添加对应于字典中某些键的值。
**请注意,您使用的是Python 2.7,因此Python 3+可能需要进行一些小的修改
class a:
global d
d={}
def get_config(self,x):
if x=='GENESYS':
d['host'] = 'host name'
d['port'] = '15222'
return d
在单独的python文件中使用类实例调用get_config方法:
from constant import a
class b:
a().get_config('GENESYS')
print a().get_config('GENESYS').get('host')
print a().get_config('GENESYS').get('port')
答案 3 :(得分:0)
def prepare_table_row(row):
lst = [i.text for i in row if i != u'\n']
return dict(rank = int(lst[0]),
grade = str(lst[1]),
channel=str(lst[2])),
videos = float(lst[3].replace(",", " ")),
subscribers = float(lst[4].replace(",", "")),
views = float(lst[5].replace(",", "")))