简体   繁体   中英

How to print all of the key/value pairs in a dictionary

Given a dictionary myDictionary , write a function that prints all of the key/value pairs of the dictionary, one per line, in the following format:

key: value
key: value
key: value

Use the following function header:

def printKeyValuePairs(myDictionary):

For example, if

myDictionary = {'The Beatles':10, 'Bob Dylan':10, 'Radiohead':5}

your function would print

The Beatles: 10
Bob Dylan: 10
Radiohead: 5
for key in myDictionary:
    print("{}: {}".format(key, myDictionary[key]))

I read on SO somewhere there is a good reason not to either access dictionary values using myDictionary[key] over the following, or visa-versa, but I can't recall where (or if I'm remembering correctly).

for key, value in myDictionary.items():
    print(f"{key}: {value}")

There are essentially two (modern) ways to do string formatting in Python, both covered in great detail [here][1]:

  • "var1: {}, var2: {}".format("VAR1", "VAR2")
  • f"var1: {"VAR1"}, var2: {"VAR2"}"

Both yield var1: var1, var2:VAR2 , but the latter is only supported in Python 3.6+.

here is a simple function that prints all the key value pairs in a dictionary:

def printKeyValuePairs(myDictionary):
"""prints each key, value pair in a line"""
    for key, val in myDictionary.items():
        print("{}: {}".format(key, val))

if the a dictionary has the following key, value pairs:

my_dict = {'The Beatles':10, 'Bob Dylan':10, 'Radiohead':5}

if we call the function defined above, we get the following output:

printKeyValuePairs(my_dict)
The Beatles: 10 
Bob Dylan: 10 
Radiohead: 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM