python-3.xdictionaryprinting

Printing dictionary keys and values on the same line, one by one in Python3


Let's say I have a dictionary: {'Mark': 100.0, 'Peter': 50.0, 'John': 25.0}

I would like to print it like this:

Mark pays 100
Peter pays 50
John pays 25

But assuming these keys and values would be inputed in to the Program, and their amount might change, how would I do it?

Somehow with a while-loop?

The problem is I don't know how to call the keys and values in a way it would always call for the next pair once the previous pair is printed.


Solution

  • If you want to use a for loop, you can use the dictionary.items() function to loop over the items of the dictionary:

    d = {'Mark': 100.0, 'Peter': 50.0, 'John': 25.0}
    for i, j in d.items():
        print (i + ' pays ' + str(j))
    

    This gives the desired output.