Python Forum
How to convert Text file contents into a dictionary.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to convert Text file contents into a dictionary.
#1
I have a text file with contents like this:
    A:B
    C:D
and so on(Its just an example).

I want to put that into a dictionary. Is it possible? If so how do I do it.


Reply
#2
Of course it is. Tell us what your ideas are. Do you know how to read files? Here's another thing to think about and to go investigate how to do: how do you separate the key from the value in the lines in your file?
Reply
#3
Ok well I have a good understanding of python. I am working on a project that sorts files and I need a place to store the extention:folderToPutIn
And working from text files is kind of time taking so I want to use dictionaries. I know how to open and do operations with files. (I have been pythoning for 1 year).
I sincerely  have no clue how to go about this.
Reply
#4
(Apr-28-2017, 05:47 AM)tannishpage Wrote: (I have been pythoning for 1 year).
I sincerely have no clue how to go about this.

Do you see the contradiction in these two statements?
Reply
#5
Open the file and read it row by row. For each line do:

dict(zip(*iter(line.split(':'))))
This will return a dictionary.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#6
(Apr-28-2017, 06:09 AM)wavic Wrote: Open the file and read it row by row. For each line do:

dict(zip(*iter(line.split(':'))))
This will return a dictionary.

what does the zip do here? and why is it *iter?

(Apr-28-2017, 06:04 AM)buran Wrote:
(Apr-28-2017, 05:47 AM)tannishpage Wrote: (I have been pythoning for 1 year). I sincerely have no clue how to go about this.
Do you see the contradiction in these two statements?
I kinda do. Sadly although I've been doing python for 1 year, I still have lots to learn. If you can, recommend books, tutorials, or something that can help me learn more. Thank you :)
Reply
#7
You can remove iter().

dict(zip(*line.split(':')))
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#8
And you can remove zip and * too and use
dict([line.split(':')])
If dict() gets only one unnamed argument, it must be either mapping or  iterable containing pairs key, value. In your case line.split(": ") returns list of two items ("pair"), so it must be "put" into some iterable - it can be done by creating list or tuple containing that pair. Wavic's unpacking and zipping works for this specific keys/values, but try it for line AB:CD or A:BC.

key, value = line.split(":")
my_dict = {key: value}
is probably more beginner friendly and more readable way to create dict.

Anyway this will always create new dictionary for each line. If you want to have same dictionary with all values, you need to either "collect" all key: value pairs and then convert them into dict at once, or create dictionary and update it for each line. Second way:
my_dict = {}
with open('file.txt') as fileobj:
  for line in fileobj:
      key, value = line.split(":")
      my_dict[key] = value
Likely you would want to use .strip() to remove end of lines ("\n").
Reply
#9
Well, I was tried dict(list(s.split(':'))) but I've got:

Error:
ValueError: dictionary update sequence element #0 has length 1; 2 is required
What is the difference between this and using square brackets?
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#10
list() used on iterable returns list containing items from that iterable, it does not return list containing given iterable. So when list() is used on list, it returns copy of given list. I guess thats for practical reasons - if it always returned list containing its argument, using list(range(5)) would give you list containing range generator instead of [0, 1, 2, 3, 4]. Same holds for tuple() and dict() behaves similarly.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question [SOLVED] Correct way to convert file from cp-1252 to utf-8? Winfried 8 543 Feb-29-2024, 12:30 AM
Last Post: Winfried
  Convert File to Data URL michaelnicol 3 1,078 Jul-08-2023, 11:35 AM
Last Post: DeaD_EyE
  Python Script to convert Json to CSV file chvsnarayana 8 2,343 Apr-26-2023, 10:31 PM
Last Post: DeaD_EyE
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,062 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Convert Excel file into csv with Pipe symbol.. mg24 4 1,288 Oct-18-2022, 02:59 PM
Last Post: Larz60+
  Need Help: Convert .pcl file to .pdf file ManuRaval 6 2,473 Sep-13-2022, 01:31 PM
Last Post: ManuRaval
  Modify values in XML file by data from text file (without parsing) Paqqno 2 1,575 Apr-13-2022, 06:02 AM
Last Post: Paqqno
  convert a named tuple to a dictionary Skaperen 13 3,387 Mar-31-2022, 07:13 PM
Last Post: Skaperen
Question How do I skipkeys on json file read to python dictionary? BrandonKastning 3 1,829 Mar-08-2022, 09:34 PM
Last Post: BrandonKastning
  trying to write a dictionary in a csv file CompleteNewb 13 6,379 Mar-04-2022, 04:43 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020