首页 > 解决方案 > 逐行打印字典数据的函数

问题描述

我一直想逐行打印字典的数据。我带着这个基本程序来了

numbers = {
    "1": "1: 345435-345-345-34",
    "2": "2: 445345-35-34-345-34",
    "3": "3: 3445-34534534-34345"

}

def print_dict(dictionary):
    for x in dictionary:
        c = dictionary[x]
        for y in c:
            print(y, ": ", dictionary[y])

print_dict(numbers)

但它给了我各种各样的错误,比如:

1 :  1: 345435-345-345-34
Traceback (most recent call last):
  File "c:\Users\pc\Documents\Bot-Programing\satesto.py", line 87, in <module>
    print_dict(numbers)
  File "c:\Users\pc\Documents\Bot-Programing\satesto.py", line 85, in print_dict
    print(y, ": ", dictionary[y])
KeyError: ':'

我要做的就是创建一个可以将字典作为参数的函数,然后像这样逐行打印它的数据:

1: 1: 345435-345-345-34
2: 2: 445345-35-34-345-34
3: 3: 3445-34534534-34345

任何帮助将不胜感激。

标签: pythonpython-3.xfunctiondictionary

解决方案


您正在迭代字典中每个键的值。相反,在 Python3.6-Python3.7 中使用f-strings或在 Python2-Python3.5 中使用字符串格式:

numbers = {
"1": "1: 345435-345-345-34",
"2": "2: 445345-35-34-345-34",
"3": "3: 3445-34534534-34345"

}
print('\n'.join(f'{a}:{b}' for a, b in numbers.items()))

Python2中的字符串格式:

print('\n'.join('{}:{}'.format(a, b) for a, b in numbers.items()))

输出:

1:1: 345435-345-345-34
2:2: 445345-35-34-345-34
3:3: 3445-34534534-34345 

推荐阅读