Home > OS >  Creating a dictionary out of a .txt file
Creating a dictionary out of a .txt file

Time:07-24

I am trying to create a python dictionary out of a txt file. The thing is, some data is always getting lost during the process of conversion.

I am trying to convert this file (its content) :

Tudo Bom;Static and Ben El Tavori;5:13;
I Gotta Feeling;The Black Eyed Peas;4:05;
Instrumental;Unknown;4:15;
Paradise;Coldplay;4:23;
Where is the love?;The Black Eyed Peas;4:13;

to a dictionary and always fail. Can you. please assist me ? My problem is that: cannot create a key-value pair for each line.

CodePudding user response:

def get_songs():
    result = []
    with open('songs.txt', 'r') as songs:  # if the file is in the same name as script
        for song in songs: # Iterates through all lines in txt file.
            song.strip()  # Strips from endline symbol.
            data = song.split(';')  # Create list with elements separated by semicolon.
            result.append(  # Adds dict to the list of dicts.
                {
                    'name': data[0],  # Access splitted elements by their positions
                    'artist': data[1],
                    'length': data[2]
                }
            )

    return result  # Returns the list with dicts.


if __name__ == '__main__':
    print(get_songs())  # Prints out returned list.

CodePudding user response:

Taking a guess at what the dictionary might look like, you could try something like this:

data = {}

with open('songs.txt') as songs:
    for n, line in enumerate(songs, 1):
        song, artist, duration, *_ = line.split(';')
        data[f'song_{n}'] = {'song':song, 'artist': artist, 'duration': duration}

print(data)

Output:

{'song_1': {'song': 'Tudo Bom', 'artist': 'Static and Ben El Tavori', 'duration': '5:13'}, 'song_2': {'song': 'I Gotta Feeling', 'artist': 'The Black Eyed Peas', 'duration': '4:05'}, 'song_3': {'song': 'Instrumental', 'artist': 'Unknown', 'duration': '4:15'}, 'song_4': {'song': 'Paradise', 'artist': 'Coldplay', 'duration': '4:23'}, 'song_5': {'song': 'Where is the love?', 'artist': 'The Black Eyed Peas', 'duration': '4:13'}}
  • Related