Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to read a file to a dictionary in python

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about how to read files into the dictionary in python. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

The most important thing to learn python is to practice, not to practice fake tricks. It is helpful to find some interesting exercises to do every day to strengthen your python skills.

Demand: the existing list.txt file stores commodity sales data, which needs to be read into the dictionary list.

Contents of the file:

Commodity, unit price, quantity

Apple, 4.8. 5.

Sydney, 2.9pm 10

Jujube, 5.8. 6.

The expected results are:

[{'Commodity': 'Apple', 'unit price': '4.8', 'quantity':'5'}

{'Commodity': 'Sydney', 'unit price': '2.9', 'quantity':'10'}

{'commodity': 'jujube', 'unit price': '5.8', 'quantity':'6'}]

First do the analysis: the file is a text file, uf8 encoding, using the open default r mode to open. The first line is judged to be the dictionary's key, followed by a line called value.

With open ('a.txtexamples, encoding='utf8') as f: name = f.readline () .strip () .split (',') # read the first line of the file into list, and key fruit_list = [] for line in f: # as a dictionary loops through handle f with for. The advantage is that no matter how large the file is, reading will not burst memory. # do not use read () or readlines (), in case the file being processed is too large to burst memory. If len (line) < 3: # filters empty rows and rows with incomplete data. Continue line = line.strip () .split (',') # separate the contents of the file by', 'into a list fruit_dict = {} # declare an empty dictionary Save the contents of each line for i in range (len (name)): # traverse the name list by subscript fruit_ [name [I]] = line [I] fruit_list.append (fruit_dict) print (fruit_list)

After writing, it feels imperfect, it is best to encapsulate it into a function, which is conducive to code reuse.

The final version is:

Def file_to_list (file):''@ param file: the parameter is the file name, and the file format is a txt file separated by','. Return: returns a list whose elements are dictionaries and the content is derived from the file file. '' with open (file, encoding='utf8') as f: name = f.readline (). Strip (). Split (',') # read the first line of the file as a dictionary key fruit_list = [] for line in f: if len (line) < 3: # filter blank lines and incomplete lines. Continue line = line.split (',') fruit_dict = {} for i in range (len (name)): # iterate through the name list, making the corresponding contents of each line into a dictionary fruit_ [name [I]] = line [I] .strip () fruit_list.append (fruit_dict) return fruit_list

At this point, read the file to the dictionary exercise is complete.

Summary:

First, when you start to learn python, you should form a good habit of modularizing the function and improving the code reuse rate and readability.

The second is to define the method to write documentation comments, method parameters and return values should be explained clearly.

Third, code comments do not have to be written on every line, the key point is to explain the code logic clearly.

The above is how to read files into the dictionary in the python shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report