-2

I have list of dict with UTF-8 and I want to save it in txt file

ls_dict = [
    { 'a': 'میلاد'},
    { 'b': 'علی'},
    { 'c': 'رضا'}
]

I want it to save in csv or txt with UTF-8

miladjurablu
  • 31
  • 1
  • 5
  • 1
    Does this answer your question? [How to dump a dict to a JSON file?](https://stackoverflow.com/questions/17043860/how-to-dump-a-dict-to-a-json-file) – Finomnis Jul 07 '22 at 07:00

3 Answers3

2

You just need to make sure you specify the relevant encoding when you create/open the output file.

import json

ls_dict = [
    { 'a': 'میلاد'},
    { 'b': 'علی'},
    { 'c': 'رضا'}
]

with open('j.json', 'w', encoding='utf-8') as j:
    j.write(json.dumps(ls_dict))

Subsequently...

with open('j.json', encoding='utf-8') as j:
    j = json.load(j)
    print(j)

Output:

[{'a': 'میلاد'}, {'b': 'علی'}, {'c': 'رضا'}]
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

you can save it as a csv using pandas

ls_dict = [
    { 'a': 'میلاد'},
    { 'b': 'علی'},
    { 'c': 'رضا'}
]

# you could flatten the list of dicts into a proper DataFrame
result = {}
for k in ls_dict:
    result.update(k)

# output from above {'a': 'میلاد', 'b': 'علی', 'c': 'رضا'}

# create DataFrame
df = pd.DataFrame(result)
#       a    b    c
# 0  میلاد  علی  رضا

# the default encoding for Pandas is utf-8
# https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html
df.to_csv('filename.csv')
Sanidhya Singh
  • 441
  • 3
  • 11
0
  • Saving the ls_dict as txt file:
import json

ls_dict = [
    { 'a': 'میلاد'},
    { 'b': 'علی'},
    { 'c': 'رضا'}
]

with open('ls_dict.txt', 'w', encoding='utf-8') as f:
    json.dump(log_stats, f,indent=2)
KingLiu
  • 59
  • 4