0

I would like to initialize an empty dictionary with the keys "001-100." I will later fill in the values.

How can I do this and then output a text file where each key:value pair is a new line in a utf-8 encoded text file? Each line should be printed as "key,value" with no quotations or spaces.

Heres what I have so far:

# Initialize the predictions dictionary
predictions = dict() 

#Output the predictions to a utf-8 txt file
with io.open("market_basket_recommendations.txt","w",encoding='utf8') as recommendations:    
    print(predictions, file = 'market_basket_recommendations.txt')
    recommendations.close()
zsad512
  • 861
  • 3
  • 15
  • 41
  • You are filling in the values *after* printing, or before? – dashiell Aug 02 '17 at 15:35
  • lol before i eventually print the dictionary, i will add the values – zsad512 Aug 02 '17 at 15:41
  • 1
    Is there a reason you don't want to just add the key value pairs as they're generated? Are there some keys that won't get values but still need to be printed? – dashiell Aug 02 '17 at 15:44
  • The only reason I want to add the values later is that I dont have them yet. Please see [link](https://stackoverflow.com/questions/45448508/frequency-based-recommendations?noredirect=1#comment77858283_45448508) – zsad512 Aug 02 '17 at 15:50

4 Answers4

1

Creating an empty dict

Use dict.from_keys(). It's specifically for building an empty dict.

predictions = dict.fromkeys("{:03}".format(i) for i in range(1, 101))
# {'001': None,
#  '002': None,
#  '003': None,
#  '004': None,
# ...

Printing on their own lines

What's more natural than using the standard print function? You can do that with redirect_stdout.

from contextlib import redirect_stdout

with open("market_basket_recommendations.txt", 'w') as file:
    with redirect_stdout(file):
        for k, v in p.items():
            print("{},{}".format(k, v))
#
# In market_basket_recommendations.txt:
#
# 001,None
# 002,None
# 003,None
# 004,None
# ...
Arya McCarthy
  • 8,554
  • 4
  • 34
  • 56
0

you can try this:

d = {i:0 for i in range(1, 101)}

f = open('the_file.txt', 'a')

for a, b in d.items():
   f.write(str(a)+" "+b+"\n")

f.close()
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • I believe that the "correct" way to write the file should be using a print statement as opposed to write. – zsad512 Aug 02 '17 at 15:40
0
# Initialize the predictions dictionary
predictions = dict({
        'a': 'value',
        'another': 'value',
    }
) 

#Output the predictions to a utf-8 txt file
with open("market_basket_recommendations.txt", "w", encoding='utf8') as recommendations:
    for key in predictions:
        recommendations.write(key + ',' + predictions[key] + '\n')

output:

another,value
a,value
Vikash Singh
  • 13,213
  • 8
  • 40
  • 70
0
with open('outfile.txt', 'w', encoding='utf-8') as f:
    for k, v in predictions.items():
        f.write(k + "," + v)
        f.write('\n')
Rahul
  • 10,830
  • 4
  • 53
  • 88