【问题标题】:How do I create a dictionary from a file using Python?如何使用 Python 从文件创建字典?
【发布时间】:2020-05-05 01:20:22
【问题描述】:

问题:如何在运行程序时打开文件并将其转换为字典?

所以我创建了一个测试字典,将其保存为 .txt 和 .dat。下面我手动输入了字典,但我希望程序在运行时打开文件,将其转换为字典,然后继续进入函数。

(程序的总体目标是输入一个密钥(productCode)来检索产品编号,所有这些都有效),但我希望它对文件进行操作,而不是手动输入的数据。

一如既往,感谢您的指导!

file = open("test.dat", "r")

FILENAME = "test.dat"


# ------ Global Variables -------
d = {'ABCD': '0123', 'HJKL': '0987'}

user_cont = True

# ------- Functions -------

print("Product number finder.")
def get_productNum2():
    global d
    user_cont = True
    while user_cont:

        productCode = input("Enter an existing product code: ")
        if productCode in d:
            productNum = d[productCode]
            print("Product #: " + productNum)
        else:
            print("Error finding product number; product code does not exist.")

        user_cont = user_continue()

def user_continue():
    global user_cont
    prompt_user = input("Do you wish to continue? Enter y/n: ")
    if prompt_user == "y":
        user_cont = True
    elif prompt_user == "n":
        user_cont = False
    return user_cont

# ------- Start Execution -------
get_productNum2()

【问题讨论】:

  • 你是如何保存你的字典的,即。保存文件的格式是什么?你腌了吗? JSON?
  • @Kos 用户输入了文件名(见下文)。对于此测试,我将其设为“test.dat”。然后我将它复制到一个 .txt 文件中,并将这些内容复制并粘贴为我的 d= {} 以测试程序的其余部分。我看到了 pickle 和 json,但觉得它超出了我目前的基础。编辑:哦,评论中的格式太糟糕了......``` FILENAME = input(str("请输入文件名:")) file = open(FILENAME, "w") file.write(str(products)) file.close() print("文件已保存。")```
  • 请解释“感觉这是我目前的基本情况”。您似乎不想使用提供的标准模块来解决您所询问的确切问题。
  • 不要只是将 dict 的字符串表示形式写入文件,这不是您进行序列化的方式。查看jsonpickle
  • @PaulCornelius 我正在编辑我的评论。它现在说“感觉它超出了我目前的基础。”看起来 JSON 和/或 pickle 是正确的选择。我还没有开始使用这些模块,只知道制作文件。

标签: python file dictionary key


【解决方案1】:

您可以(并且应该)将字典写入 JSON 格式的文件。它不仅以人类可读的方式保存,JSON 格式还意味着字典甚至可以根据需要加载到许多其他编程语言和程序中!

这里是一个使用标准库包json的例子:

import json

dict = {'ABCD': '0123', 'HJKL': '0987'}

dict_json = json.dumps(dict) #this line turns the dictionary into a JSON string
with open("my_dictionary.json", "w") as outfile:
    outfile.write(dict_json) 

给定一个 JSON 格式的字典,我们可以这样加载它:

with open("my_dictionary.json", "r") as infile: 
    dict = json.load(infile) 

现在您可以访问从文件中加载的dict,就好像它是原始字典一样:

>>> print(dict["ABCD"])
0123

【讨论】:

    猜你喜欢
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    相关资源
    最近更新 更多