Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using join() on dictionary in python to return key value pairs as one long string

I want to join() key and value pairs in a my dictionary with a : inbetween. I want to return it all as one string.

Intuitivly I hoped just plugging the dictionary in would work:

def format_grades(grades):


    return ': '.join(grades) + "\n" 

I tried something like this ': '.join(str(n) for n in grades[n]) to convert my values to strings since my dict looks like this: {john: 2} but I can't think straight now, ideas?

like image 492
Zimbabaluba Avatar asked Sep 08 '26 14:09

Zimbabaluba


1 Answers

Using f-strings in python3 - you can iterate over the items in the dict and print each on a new line.

print("\n".join(f'{k}: {v}' for k,v in grades.items()))

Example:

grades = {'john': 2, 'marry': 4}
print("\n".join(f'{k}: {v}' for k,v in grades.items()))

Output:

john: 2
marry: 4
like image 90
rdas Avatar answered Sep 11 '26 02:09

rdas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!