how to make text file of List of Dict python

Question:

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

Asked By: miladjurablu

||

Answers:

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': 'رضا'}]
Answered By: Vlad

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')
Answered By: Sanidhya Singh
  • 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)
Answered By: KingLiu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.