Search code examples
pythonlistfiledictionaryfilenames

How to name a file using a value in a list in a dictionary?


For example I have a list inside a dictionary:

{'results': [{'name': 'sarah', 'age': '18'}]}

I want make a text file and the name of file must be the value of dict 'name' ex: sarah.txt.

How should I code it in python?


Solution

  • Something like this:

    dictionary = {'results': [{'name': 'sarah', 'age': '18'}]}
    name = dictionary['results'][0]['names'] + '.txt'
    open(name, "w")
    

    Opening a file in the write mode, if it doesn't exist already, will create a new file with that name.