Python-读取文件并另存为数组

Python-读取文件并另存为数组,python,arrays,list,Python,Arrays,List,我是新来的,我有一个问题要问。我需要为我的学校做一些练习,我们现在使用Python作为语言。Python对我来说是一种新语言。所以我的问题是: 我们需要打开一个包含超市价格列表的文本文件,如下所示: {"rice": 2.10, "orange":3.31, "eggs":1.92, "cheese":8.10, "chicken":5.22} 如何打开此文件并将其转换为数组或其他可以使用的文件? 此外,我需要将此列表作为散列数组(命名自PowerShell),以便在下一步使用列表的产品进行计

我是新来的,我有一个问题要问。我需要为我的学校做一些练习,我们现在使用Python作为语言。Python对我来说是一种新语言。所以我的问题是:

我们需要打开一个包含超市价格列表的文本文件,如下所示:

{"rice": 2.10,
"orange":3.31,
"eggs":1.92,
"cheese":8.10,
"chicken":5.22}
如何打开此文件并将其转换为数组或其他可以使用的文件?
此外,我需要将此列表作为散列数组(命名自
PowerShell
),以便在下一步使用列表的产品进行计算。

在我看来,您拥有的文件是JSON格式的(我可能错了)。这可以很容易地读入
dict

我已经创建了包含数据的文件
test.dat
。然后你只需做:

$ python3
Python 3.7.5 (default, Oct 22 2019, 10:35:10)
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> with open("test.dat") as f:
...     data = json.loads(f.read())
...     print(data)
...     print(data["rice"])
...
# data is now a dict which is a key=>value container
# you can see it like:
{'rice': 2.1, 'orange': 3.31, 'eggs': 1.92, 'cheese': 8.1, 'chicken': 5.22}
# you can also access individual keys like data["rice"] in this case
2.1

您可以阅读更多关于JSON和python字典(即hashmaps)的信息。

这是否回答了您的问题?也许你想要。@ycao我认为“json”是这里缺少的部分…非常感谢你的帖子!缺少的部分是json,它工作正常。