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.
#11
Except it returns a list:

In [1]: list(range(5))

Out[1]: [0, 1, 2, 3, 4]
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#12
(Apr-28-2017, 08:35 AM)wavic Wrote: Except it returns a list:

In [1]: list(range(5))

Out[1]: [0, 1, 2, 3, 4]
Isnt it exactly what i posted?
(Apr-28-2017, 08:30 AM)zivoni Wrote: list() used on iterable returns list containing items from that iterable,..
...
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].
I tried to write second sentence as some sort of "unreal conditional", but my english is pretty weak...
Reply
#13
>>> line = "key:value"
>>> dict(list(line.split(":")))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 3; 2 is required
>>> dict([line.split(":")])
{'key': 'value'}
>>> list(line.split(":"))
['key', 'value']
>>> [line.split(":")]
[['key', 'value']]
dict() expects a list of key-value pairs. If you use list(), you'll just have a list of strings, and not a list of key-value pairs.
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 545 Feb-29-2024, 12:30 AM
Last Post: Winfried
  Convert File to Data URL michaelnicol 3 1,080 Jul-08-2023, 11:35 AM
Last Post: DeaD_EyE
  Python Script to convert Json to CSV file chvsnarayana 8 2,344 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,064 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,474 Sep-13-2022, 01:31 PM
Last Post: ManuRaval
  Modify values in XML file by data from text file (without parsing) Paqqno 2 1,576 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,831 Mar-08-2022, 09:34 PM
Last Post: BrandonKastning
  trying to write a dictionary in a csv file CompleteNewb 13 6,381 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