How to format dictionary?

Question:

I have this function:

def total_fruit_per_sort():
    number_found = re.findall(total_amount_fruit_regex(), verdi50)
   
    fruit_dict = {}
    for n, f in number_found:
        fruit_dict[f] = fruit_dict.get(f, 0) + int(n)
        
    return pprint.pprint(str( {value: key for value, key in fruit_dict.items() }).replace("{", "").replace("}", "").replace("'", ""))


print(total_fruit_per_sort())

But it prints the values like: 'Watermeloenen: 466, Appels: 688, Sinaasappels: 803'

But I want them under each other, like this:

Watermeloenen: 466
Appels: 688
Sinaasappels: 803

Question: how to archive this?

Asked By: mightycode Newton

||

Answers:

In some ways, the issue is that you are passing a string to pprint which has already been formatted.

Maybe add .replace(',' , 'n') at the end of the string before printing?


Using pprint, I think this would be the best way to format the dictionary (D):

print(pprint.pformat(D,width=1)[1:-1].replace('n ','n').replace("'",'').replace('"','').replace(',',''))

But I guess a direct one-liner for-loop looks nicer:

print('n'.join(f'{k}: {v}' for k,v in D.items()))
Answered By: C-3PO

You don’t need pprint for this

result = 'n'.join(f'{key}: {val}' for key, val in your_dict.items())
Answered By: gog
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.