如何返回字典 | Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17713683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:59:15  来源:igfitidea点击:

How to return a dictionary | Python

pythonpython-3.x

提问by CommonCoreTawan

I have a .txt file with the following lines in it:

我有一个 .txt 文件,其中包含以下几行:

23;Pablo;SanJose
45;Rose;Makati

I have this program:

我有这个程序:

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

So what's happening (according to me) is:

所以正在发生的事情(根据我的说法)是:

File is opened A hash called tableis created and each line of the file is split into 3 keys/values. If the identered by the user matches the value of the key ID, then close the file and return the whole hash.

文件被打开table创建一个名为的散列,文件的每一行被分成 3 个键/值。如果id用户输入的值与 key 的值匹配ID,则关闭文件并返回整个哈希值。

Then, I'm assigning table2the values on the tablehash and I'm trying to print the values in it.

然后,我table2table散列上分配值,并尝试打印其中的值。

When I run this, I get the following:

当我运行它时,我得到以下信息:

   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'

It seems like it's not recognizing the key IDon the table2var. I also tried declaring table2as a hash by putting table2 = {}before the function is executed, but it continues to display the error message.

它似乎无法识别varID上的键table2。我还尝试table2通过table2 = {}在函数执行之前放置来声明为散列,但它继续显示错误消息。

How do I assign the values of a returned hash to a variable, so that I can print them using their keys?

如何将返回的哈希值分配给变量,以便我可以使用它们的keys?

采纳答案by Gabe

What's going on is that you're returning right after the first line of the file doesn't match the id you're looking for. You have to do this:

发生的事情是您在文件的第一行与您要查找的 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 {}

回答by Vaibhav Shukla

I followed approach as shown in code below to return a dictionary. Created a class and declared dictionary as global and created a function to add value corresponding to some keys in dictionary.

我按照下面的代码所示的方法返回字典。创建了一个类并将字典声明为全局,并创建了一个函数来添加与字典中某些键对应的值。

**Note have used Python 2.7 so some minor modification might be required for Python 3+

**注意使用了 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

Calling get_config method using class instance in a separate python file:

在单独的 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')

回答by gaurav raj

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(",", "")))