Python Forum
dictionary output to text file (beginner)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dictionary output to text file (beginner)
#1
I'm trying to learn Python and I got stuck on something.
I'm looping through a dictionary and I'm printing out keys and their associated dictionary values.
I now want to take this output from my loop and instead of printing it to the screen, I need to write it to a text file.

here is an exmple from the web-
with open('datafile1.txt', 'a') as f:
    f.write('\n')
    f.write('monkey')
    f.write('\n')
    f.write(str(15))
I understand how this works, but how do I do the same for my loop? To further complicate things, I don't know if any of my data will throw an error because
its value is numneric and not a string.

Here is my loop that correctly prints my dictionary elements and values.
I need help in how I can redirect the output to a text file.

print("\nThis prints the key and its associated values")
for person in data['returnData']:
     print(f"Elid: {person['elid']}, Last Name: {person['name']}")
Thanks for taking a look.
Delg
buran write Jul-11-2023, 03:41 PM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.

Attached Files

.py   json_parser_1.py (Size: 25.76 KB / Downloads: 96)
Reply
#2
You could do that like this. First I need a dictionary containing some data:

# open any old text file
mytext = '/home/pedro/summer2023/breakingnewsenglish/UK_rationing.txt'
with open(mytext) as t:
    data = t.readlines()
print('data list is', len(data), 'long')
# make a dictionary
# all the keys are integers in this case, all the values are lines of text
mydict = {i:data[i] for i in range(len(data))}
# show the content of mydict
for item in mydict.items():
    print(item)
Now get some data from the dictionary and put it in a list

# an empty list to take the dictionary items you want to save in a text file
mylist = []
# just get the first 9 lines
for i in range(10):
    mylist.append(mydict[i])
# show the things to be saved to text
for m in mylist:
    print(m)
Now make the list into a string and write the string to the text file

# join the list to a string
# it is better to make a list than to create strings
# strings take up much more memory because they persist, so I have been told
mystring = ''.join(mylist)
# write the string to a text file
dict2text = '/home/pedro/summer2023/breakingnewsenglish/UK_rationing_part.txt'
with open(dict2text, 'w') as out:
    out.write(mystring)
    print('Some text from a dictionary saved as', dict2text)
3 steps to heaven! have fun learning!
Reply
#3
You can tell print() to print to a file.:
with open('datafile1.txt', 'a') as f:
    print("\nThis prints the key and its associated values")  # Prints to terminal
    for person in data['returnData']:
        print(f"Elid: {person['elid']}, Last Name: {person['name']}", file=f)  # Prints to file
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  to find in dictionary given parameter 'name' and to output position Liki 10 1,232 Oct-08-2023, 06:38 AM
Last Post: Pedroski55
  Output File ? Kessie1971 11 1,855 May-11-2023, 08:31 AM
Last Post: buran
  beginner having text based adventure trouble mrgee 2 2,032 Dec-16-2021, 05:07 AM
Last Post: buran
  Using dictionary to find the most sent emails from a file siliusu 6 7,452 Apr-22-2021, 06:07 PM
Last Post: siliusu
  Updating dictionary in another py file tommy_voet 1 4,782 Mar-28-2021, 07:25 PM
Last Post: buran
  Making a dictionary from a file instyabam 0 1,481 Oct-27-2020, 11:59 AM
Last Post: instyabam
  how can i create a dictionary of dictionaries from a file Astone 2 2,209 Oct-26-2020, 02:40 PM
Last Post: DeaD_EyE
  Convert all actions through functions, fill the dictionary from a file Astone 3 2,369 Oct-26-2020, 09:11 AM
Last Post: DeaD_EyE
  Read text file, process data and print specific output Happythankyoumoreplease 3 2,851 Feb-20-2020, 12:19 PM
Last Post: jefsummers
  Parse text from a .txt file and save multiple output .txt rattlerskin 10 10,901 Aug-25-2019, 08:50 PM
Last Post: dwirsig

Forum Jump:

User Panel Messages

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