【问题标题】:How to return python dictionary to use in other function?如何返回python字典以在其他功能中使用?
【发布时间】:2018-11-09 20:25:04
【问题描述】:

在这个函数中,我从 .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)

【问题讨论】:

  • 你每次循环都会覆盖你的字典,那么你想完成什么?你想要一个字典列表吗?在我看来,字典中的键应该是每个client_id,值是包含其他属性的字典。
  • 只返回-txt文件的第一行
  • 我想要一本字典,格式如下:{'client_id': 'id: 8914ba03', 'coordinates': {'lat': ' lat: 51.47100685', 'long': ' long:16.29731236'}} 在我看来我没有覆盖它,因为我可以设法打印出整个东西?但我不能肯定地说是这样。我认为分配键和值的循环原则正在起作用......我只想能够在另一个函数中使用字典。
  • 您打印它,然后在下一次循环中覆盖它。您可能只想追加到一个列表并在循环结束时返回它。

标签: python return yield


【解决方案1】:

您的代码中有一些错误。

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

【讨论】:

  • if line 将始终为真,因为line 至少为'\n'(否则迭代器将停止)。你想要element = line.split(","),然后是if element可能为空)
  • 非常感谢奥利弗,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2021-04-03
  • 2016-07-05
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
相关资源
最近更新 更多