如何将 return python 词典用于其他功能?

How to return python dictionary to use in other function?

在这个函数中,我从 .txt 文件中读取,并将值存储在字典中。我希望能够将此字典传递给另一个函数,以进行进一步的计算和排序。

我可以打印 .txt 文件中的所有行,但仅此而已。

Return 打破循环,只给出第一行。

全局变量和嵌套函数的格式不正确。

曾尝试使用 yield(第一次),但只打印 "generator object get_all_client_id at 0x03369A20"

file_with_client_info = open("C:\Users\clients.txt", "r")

def get_all_client_id():
    client_details = {}

     for line in file_with_client_info:
        element = line.split(",")
        while element:
            client_details['client_id'] = element[0]
            client_details['coordinates'] = {}
            client_details['coordinates']['lat'] = element[1]
            client_details['coordinates']['long'] = element[2]
            break

        print(client_details)

您的代码中存在一些错误。

  1. 使用return语句输出字典。

  2. while 循环 不会循环,因为您在第一次迭代时就中断了。使用 if 语句 来检查该行是否为空。

  3. 每次迭代都会覆盖 client_details 字典中的最后条目。创建一个新条目,可能使用 client_id 作为键。

  4. 建议您使用 with 上下文管理器打开您的文件。

  5. 最好向函数提供文件名并让它打开它,而不是全局打开文件。

这是您的代码的固定版本。

def get_all_client_id(file):
    client_details = {}

    with open(file, 'r') as f:
        for line in f:
            element = line.strip().split(',')
            if element:
                client_id, lat, long, *more = element
                client_details[client_id] = {'lat': lat, 'long': long}

    return client_details

clients_dict = get_all_client_id("C:\Users\clients.txt")