Python reads contents from file into dictionary
Reading Content from a File into a Dictionary in Python
In Python, dictionaries are a very common data type. What if we need to read data stored in a file into a dictionary? This article will show you how to use Python to read content from a file into a dictionary.
Preparation
Before we begin reading files, we need to prepare the data file. Assume we have a file called data.txt
with the following contents:
apple,1.50
banana,2.30
orange,1.80
This file stores three fruits and their prices. Each fruit and price is separated by a comma ,
.
Reading File Contents into a Dictionary
Next, we need to write Python code to read the contents of this file and store them in a dictionary. The code is as follows:
fruits = {}
with open("data.txt", "r") as f:
for line in f:
line = line.strip().split(",")
fruits[line[0]] = float(line[1])
print(fruits)
The above code uses the Python file operation function open()
to open the file. r
means opening the file in read-only mode. The with
statement ensures that the file is automatically closed after the file operation is completed.
Next, we use the for
loop to iterate over each line of the file, use the strip()
function to remove the whitespace characters at the end of each line, and use the split(",")
function to separate each line into two parts by commas and assign them to the line
list. Next, we set the key in the dictionary to line[0]
and the corresponding value to float(line[1])
.
Finally, we use the print()
function to output the read dictionary. Running the code produces the following output:
{'apple': 1.5, 'banana': 2.3, 'orange': 1.8}
As you can see, we successfully read the contents of the file into the dictionary.
Handling Exceptions
When reading files directly, we also need to be aware of some possible exceptions, such as failure to open the file. Therefore, we need to implement error handling in the code. The modified code is as follows:
fruits = {}
try:
with open("data.txt", "r") as f:
for line in f:
line = line.strip().split(",")
fruits[line[0]] = float(line[1])
print(fruits)
except FileNotFoundError:
print("File not found!")
except Exception as e:
print("Error:", e)
We put the entire read operation in the try
block. When an exception occurs, the program will jump to the corresponding except
block. When the file is not found, the program will output File not found!
; otherwise, it will output Error: xxx
.
Conclusion
This article introduced how to use Python to read file contents into a dictionary and handled possible exceptions. Reading files and storing data in a dictionary is a common operation in Python, and mastering this skill is very useful for processing large data files.