如何整齐地打印字典里面的词典

时间:2016-10-23 22:42:21

标签: python dictionary printing nested

我使用以下代码:

sick = {"Carson": {"Reason": "Broken leg on P coy", "Expiry": "2017-1-4"}, "Jackson": {"Reason": "Fell over tree root on exercise", "Expiry": "2017-2-3"}, "Ben": {"Reason": "Tripped", "Expiry": "2018-7-6"}}

def showsick():
    print "=" * 10
    print "Personnel on sick:"
    for name, reason, expiry in sick.iteritems():
        print name, ": ", reason, "\nSick chit expires: ", expiry, "\n"
    print "=" * 10
    main()

尝试生成这样的输出:

Carson: Broken leg on P coy
Sick chit expires: 2017-1-4

Jackson: Fell over tree root on exercise
Sick chit expires: 2017-2-3

Ben: Tripped
Sick chit expires: 2018-7-6

但我得到“ValueError:需要超过2个值才能解压缩”。我尝试了很多不同的东西,包括玩json(非常简短)和pprint(再简单),以及其他一些小东西。我不能让它工作

2 个答案:

答案 0 :(得分:2)

iteritems一次只生成两对 - 键和值 - 因此您无法在for循环中解压缩为三个项目。

相反,你想做:

for name in sick:
     print name, ": ", sick[name]['Reason']
     print "Sick chit expires: ", sick[name]['Expiry']

答案 1 :(得分:2)

你的生病功能应该是:

def showsick():
    print "=" * 10
    print "Personnel on sick:"
    for person, nested_dict in sick.iteritems():
        print person, ': ', nested_dict['Reason']
        print 'Sick chit expires: ', nested_dict['Expiry']
    print "=" * 10

您的代码问题是:dict.iteritems()返回(key, value)对的元组。因此,您可以将其包含在for中,只包含两个变量:

 for x, y in dict.iteritems():
 #   ^  ^    <-- only two variables, since .iteritems() returns tuple pair of 2

在您的代码中,y(在我的示例中)也是dict。要从中获取价值,您需要执行y[key]

示例输出:

>>> showsick()
==========
Personnel on sick:
Carson :  Broken leg on P coy
Sick chit expires:  2017-1-4
Ben :  Tripped
Sick chit expires:  2018-7-6
Jackson :  Fell over tree root on exercise
Sick chit expires:  2017-2-3
==========