This site uses Akismet to reduce spam. Learn how your comment data is processed. By Krunal Last updated Jan 12, 0. Krunal posts comments.
You might also like More from author. Prev Next. Leave A Reply. Home Programming Python Javascript Node. As a Data Analyst or Data scientist when we have huge data in files then we need to convert that data into python objects. This conversion helps us in handling the data in an organized manner. We will learn about one of the use cases where we will be converting the text file data to a Python dictionary object.
To understand this, We will take a sample text file and will read the content, and load it in the Python dictionary. So to start with, Let us Assume, we have the following text file lang. Now let us jump into the details of the program and learn each step with the explanation. To start with the process first we will create an empty dictionary that will hold the file data in the form of dictionary data.
The methods dict. There's also an items which returns a list of key, value tuples, which is the most efficient way to examine all the key value data in the dictionary. All of these lists can be passed to the sorted function. There are "iter" variants of these methods called iterkeys , itervalues and iteritems which avoid the cost of constructing the whole list -- a performance win if the data is huge.
However, I generally prefer the plain keys and values methods with their sensible names. In Python 3 revision, the need for the iterkeys variants is going away. Strategy note: from a performance point of view, the dictionary is one of your greatest tools, and you should use it where you can as an easy way to organize data.
For example, you might read a log file where each line begins with an IP address, and store the data into a dict using the IP address as the key, and the list of lines where it appears as the value. Once you've read in the whole file, you can look up any IP address and instantly see its list of lines.
The dictionary takes in scattered data and makes it into something coherent. The "del" operator does deletions. In the simplest case, it can remove the definition of a variable, as if that variable had not been defined. Del can also be used on list elements or slices to delete that part of the list and to delete entries from a dictionary. The open function opens and returns a file handle that can be used to read or write a file in the usual way.
0コメント