Python Forum
how to read a dictionary line from txt file?
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to read a dictionary line from txt file?
#1
Hey! I have a txt file with multiple dictionary lines. How could I possible read it literally as a dictionary line or straight as a dictionary line value in to the python file?
my txt file:
{'Cost': 22, 'Income': 1, 'Month': 'a', 'Cash1': 23, 'Cash2': 2, 'Investments': 3}
{'Cost': 22, 'Income': 1, 'Month': 'b', 'Cash1': 23, 'Cash2': 2, 'Investments': 3}
{'Cost': 22, 'Income': 1, 'Month': 'c', 'Cash1': 23, 'Cash2': 2, 'Investments': 3}

I was trying this way, but yet it still reads data as a string..

    def Chart_data(self):        
        with open('abc.txt') as f:
            data = []            
            for line in (line for line in f if line.rstrip('\n')):
                data.append(int(eval(line['Cash1'])))
Many thanks for your help!
Reply
#2
Are you creating the file? Because it'd be much easier if it wasn't in this format. If you could somehow get json/yaml, or even a pickle file, that'd be simple to do.

If that's not possible, I'd suggest using a regular expression to parse the line.

For example, here's a rough looking regex which works for your sample data:
>>> lines = '''{'Cost': 22, 'Income': 1, 'Month': 'a', 'Cash1': 23, 'Cash2': 2, 'Investments': 3}
... {'Cost': 22, 'Income': 1, 'Month': 'b', 'Cash1': 23, 'Cash2': 2, 'Investments': 3}
... {'Cost': 22, 'Income': 1, 'Month': 'c', 'Cash1': 23, 'Cash2': 2, 'Investments': 3}'''.split('\n')
>>> import re
>>> regex = re.compile(r"('([^']+)':\s+'?([^,'}]+)'?,?\s*)")
>>> dicts = []
>>> for line in lines:
...   groups = regex.findall(line)
...   object = {}
...   for group in groups:
...     object[group[1]] = group[2]
...   dicts.append(object)
...
>>> for obj in dicts:
...  print(obj)
...
{'Cost': '22', 'Income': '1', 'Month': 'a', 'Cash1': '23', 'Cash2': '2', 'Investments': '3'}
{'Cost': '22', 'Income': '1', 'Month': 'b', 'Cash1': '23', 'Cash2': '2', 'Investments': '3'}
{'Cost': '22', 'Income': '1', 'Month': 'c', 'Cash1': '23', 'Cash2': '2', 'Investments': '3'}
Reply
#3
If you're going to use eval, just eval the whole line. But don't use eval if you don't trust where the data is coming from.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Recommended way to read/create PDF file? Winfried 3 2,867 Nov-26-2023, 07:51 AM
Last Post: Pedroski55
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,427 Nov-09-2023, 10:56 AM
Last Post: mg24
  read file txt on my pc to telegram bot api Tupa 0 1,104 Jul-06-2023, 01:52 AM
Last Post: Tupa
  parse/read from file seperated by dots giovanne 5 1,103 Jun-26-2023, 12:26 PM
Last Post: DeaD_EyE
  Formatting a date time string read from a csv file DosAtPython 5 1,250 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  How do I read and write a binary file in Python? blackears 6 6,496 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  Read csv file with inconsistent delimiter gracenz 2 1,192 Mar-27-2023, 08:59 PM
Last Post: deanhystad
  Python Serial: How to read the complete line to insert to MySQL? sylar 1 817 Mar-21-2023, 10:06 PM
Last Post: deanhystad
  File "<string>", line 19, in <module> error is related to what? Frankduc 9 12,540 Mar-09-2023, 07:22 AM
Last Post: LocklearSusan
  Read text file, modify it then write back Pavel_47 5 1,585 Feb-18-2023, 02:49 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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