Home>

I want to preserve the dictionary function when I save the dictionary type data once as text data and call it in another file.
For example

{
'Name': ['John', 'Kawakami', 'Ueda', 'Paul'],
'Gender': ['woman', 'woman', 'woman', 'woman'],
'E-mail address': ['[email protected]', '[email protected]', '[email protected]', '[email protected]']
}

Suppose you have dictionary data such as

. When I save this data as txt data, I want to use it in another file.
However, if it is called as text data, it will be treated as a list or character string and will not function as a dictionary.

Is there a way to use it as a dictionary?

Try it,

def write_txt (type_of_dictionary):
    with open ('sample_w2.txt', 'w') as f:
        for k, v in type_of_dictionary.items ():
            if sorted (type_of_dictionary.keys ()) [0] == k:
               print ('run')
               f.write ('{' + '{0}'. format (k) + ':' + str (v) + '\ n')
            f.write ('{0}'. format (k) + ':' + str (v) + '\ n')
            if sorted (type_of_dictionary.keys ()) [len (type_of_dictionary.keys ())-1] == k:
               print ('end')
               f.write ('{0}'. format (k) + ':' + str (v) + '}')

Now, the text data is saved as a dictionary-like shape, but because it is written as a string,
When reading with another file and specifying key, it is said that key does not exist in the list.

By the way,
ast library literal_eval ()
Was used but didn't work.

  • Answer # 1

    Please save in json format.
    You can easily save it as a dictionary, and you can use it as it is.

    If you specify ensure_ascii = False for json.dump, Japanese can be output.

Related articles