Zimbabaluba
Zimbabaluba

Reputation: 588

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?

Upvotes: 3

Views: 7882

Answers (3)

Preetham
Preetham

Reputation: 577

def format_grades(grades):

return ( "\n".join([str(i[0])+":"+str(i[1]) for i in grades.items()]) )

Upvotes: 2

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

You can iterate over the keys and values, and make the string by joining them

grades = {'Joe':'A','John':'B'}
print(" ".join('{}: {}'.format(k,v) for k,v in grades.items()))
#Joe: A John: B

Upvotes: 2

rdas
rdas

Reputation: 21275

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

Upvotes: 9

Related Questions