Search code examples
pythonpython-3.xdata-sciencepython-datamodel

From a python dictionary how do I save the key and value to a *.txt file


How do I print the key and value to a *.txt file from a dictionary?

I have tried to read the data and to print it to a *.txt file but the name.txt file is empty.

#The code that I have tried
#my_dict is given above
def create_dict():

    with open("name.txt", "w+") as f:
    for key, value in my_dict:
            print(key, value)
            f.write('{} {}'.format(key, value))

Solution

  • As other answers pointed out, your indentation is simply wrong inside your with statement.

    Pickle

    Although, if your goal is to save a dictionary for later use, your best bet is probably to use pickle. This will not do the trick if your intent is to have the dictionary saved in a human-readable format, but will be way more efficient as a data-storage method.

    import pickle
    
    my_dict = {
        'foo': 'bar',
        'baz': 'spam'
    }
    
    # This saves your dict
    with open('my_dict.p', 'bw') as f:
        pickle.dump(my_dict, f)
    
    # This loads your dict
    with open('my_dict.p', 'br') as f:
        my_loaded_dict = pickle.load(f)
    
    print(my_loaded_dict)  # {'foo': 'bar', 'baz': 'spam'}
    

    Json

    A compromise between storage efficiency and readability might be to use json instead. It will fail for complex Python objects which are not JSON serializable, but is a perfectly valid storage method nonetheless.

    import json
    
    my_dict = {
        'foo': 'bar',
        'baz': 'spam'
    }
    
    # This saves your dict
    with open('my_dict.json', 'w') as f:
        # passing an indent parameter makes the json pretty-printed
        json.dump(my_dict, f, indent=2) 
    
    # This loads your dict
    with open('my_dict.json', 'r') as f:
        my_loaded_dict = json.load(f)
    
    print(my_loaded_dict)  # {'foo': 'bar', 'baz': 'spam'}