August Williams
August Williams

Reputation: 929

How to insert newline character into a dictionary value?

I have a nested dictionary that stores a collection of MP3's and their music. The first level dictionary stores the MP3's themselves and the second level dictionary stores capacity and music information. The dictionary could be:

{'mp3One': {'Capacity': 50, 'songOne': 50}, 'mp3Two': {'Capacity': 150}}

I would like to insert newline characters after the value in the second level dictionary, so that when printed it would look something like this:

{'mp3One': {'Capacity': 50, 
            'songOne': 50 }, 
 'mp3Two': {'Capacity': 150}
}

This way, I can have a newline character after every song, or capacity. Currently, the key and value for music are added with this line:

mp3Collection[MP3Name][songName] = songSize

I have tried using sting concatenation with \n:

mp3Collection[MP3Name][songName] = str(songSize) + "\n"

But this adds "\n" to the dictionary value, rather than a newline. I understand this could be done using string formatting? But I'm not really sure how to go about it.

Upvotes: 0

Views: 10815

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160587

You could just supply this to pprint with a really small width, that should print it out the way you need by forcefully adding new lines after every comma in order for it to comply as much as it can to the width:

>>> import pprint
>>> d = {'mp3One': {'Capacity': 50, 'songOne': 50}, 'mp3Two': {'Capacity': 150}}
>>> pprint.pprint(d, width=1)
{'mp3One': {'Capacity': 50,
            'songOne': 50},
 'mp3Two': {'Capacity': 150}}

altering the dictionary and adding a new line won't affect output formatting, you need to take care of the formatting either with pprint or by looping and adding printing '\n'

Upvotes: 4

Related Questions