简体   繁体   English

如何打印字典中的所有键/值对

[英]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:给定一个字典myDictionary ,编写一个函数来打印字典的所有键/值对,每行一个,格式如下:

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).我在 SO 某处阅读,有充分的理由不使用myDictionary[key]访问字典值,反之亦然,但我不记得在哪里(或者如果我没记错的话)。

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]:基本上有两种(现代)方法可以在 Python 中进行字符串格式化,[这里][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+.两者都产生var1: var1, var2:VAR2 ,但后者仅在 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:如果 a 字典具有以下键值对:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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