1

I am unable to write a dictionary to file using json.dump due to having Hebrew letters and the file just contains trash in English letters.

import codecs

if __name__ == '__main__':
    k = dict()
    k['tony ta'] = 4
    k['tt '] = 5
    l = list(k)
    with codecs.open('text.txt', 'w', 'utf-8') as f:
        for i in range (0, len(l)):
            f.write('\n'+(l[i]) + ' ' + str(k[l[i]]))

Using codecs I am able to write it correctly and obtain the result I want. For this demo I'm using open. Is there a more convenient way to do this ?

text.txt
tony ta 4
tt 5

Any better way rather than having to turn my dictionary to list and then access the dictionary to find the value ?

Tony Tannous
  • 14,154
  • 10
  • 50
  • 86

2 Answers2

1

So instead of converting the dictionary to a list, I converted it into a string and then did some string operation. I am not sure if you will consider this a "better" or a "more convenient" way.

import codecs
import re

if __name__ == '__main__':
    k = dict()
    k['tony ta'] = 4
    k['tt '] = 5
    with codecs.open('text.txt', 'w', 'utf-8') as f:
        f.write(re.sub(r"[{}:']",'',str(k).replace(', ','\n')))
Mia
  • 2,466
  • 22
  • 38
1

you could use :

with codecs.open('text.txt', 'w', 'utf-8') as f:
    for key in k:
        f.write("%s %s\n", key, str(k[key]))
Ajay Singh
  • 1,251
  • 14
  • 17