0

I am new here and I have a question for the start. I need to do some exercises for my school and there we use now Python as language. Python is a new language for me. So my problem is:

We need to open a text-file with a list of prices for a supermarket, like this:

{"rice": 2.10,
"orange":3.31,
"eggs":1.92,
"cheese":8.10,
"chicken":5.22}

How can I open this file and convert it into a array or something else, that i can work with it? Furthermore I need this list as a hash array (named from PowerShell) to calculate in the next step with the products of the list.

Santosh Aryal
  • 1,276
  • 1
  • 18
  • 41
ziBBer
  • 5
  • 2

1 Answers1

0

It seems to me that the file you have is JSON format (I might be wrong). This can be very easily read into a dict.

I have created the file test.dat which contains the data. Then you simply do:

$ 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

You can read more about JSON here and about python dictionaries (ie hashmaps) here

urban
  • 5,392
  • 3
  • 19
  • 45