逐行打印字典数据的功能

时间:2018-08-15 21:26:47

标签: python python-3.x function dictionary

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

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

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您正在遍历字典中每个键的值。相反,请在Python3.6-Python3.7中使用{ "name": "Nasdaq_Webhook", "event_type": "response_completed", "object_type": "survey", "object_ids": ["155794502"], "subscription_url": "https://e2-impl-cci.workday.com/ccx/cc-cloud-repo/launches/INT057_Test/INT057_Test/StartHere", "authorization": "Basic {username/pw hash}" } 或在Python2-Python3.5中使用字符串格式:

f-strings

Python2中的字符串格式:

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()))

输出:

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

答案 1 :(得分:0)

您只需要遍历键和值。

for i in numbers:
    print("{}: {}".format(i, numbers[i]))

我使用的.format()参数是格式化字符串的有用工具,它仅将变量放置在字符串中{}所在的位置。参见文档here