如何在字典中输出列表的索引号?

时间:2018-04-15 03:13:25

标签: python

我有一个字典,其中包含一个包含多个值的列表,我应该有一个show方法来输出这种格式的字典

"
2017-02-12:
    0: Eye doctor
    1: lunch with sid
    2: dinner with Jane
2017-03-29:
    0: Change oil in blue car
    1: Fix tree near front walkway
    2: Get salad stuff
2017-05-06:
    0: Sid's birthday"

然而,使用我的代码,我只能让它显示如下

2017-02-12:
    Eye doctor
    lunch with sid
    dinner with Jane
2017-03-29:
    Change oil in blue car
    Fix tree near front walkway
    Get salad stuff
2017-05-06:
    Sid's birthday

我不知道如何在值本身之前显示索引号。我该怎么办? 这是我目前的代码

def command_show(calendar):
    for i in calendar:
        print("    "+ i +":")
        for l in calendar[i]:
            print("        ", l)

提前致谢。

2 个答案:

答案 0 :(得分:0)

def command_show(calendar):
    for key, value in calendar.items():
    print(key + ':\n')              
    for l in calendar[key]:         
        print("    " + str(list(calendar[key].keys()).index(l)), calendar[key][l])            

说明:

打印日历日期:

 print(key + ':\n')

迭代每个日期的嵌套字典:

 for l in calendar[key]:

列出每个日期的嵌套字典键:

 list(calendar[key].keys())

获取密钥的索引:

 str(list(calendar[key].keys()).index(l))

答案 1 :(得分:0)

您可以尝试这种方法:

calendar={'2017-05-06': ["Sid's birthday"], '2017-03-29': ['Change oil in blue car', 'Fix tree near front walkway', 'Get salad stuff'], '2017-02-12': ['Eye doctor', 'lunch with sid', 'dinner with Jane']}

for i in calendar:
    print("    "+ i +":")
    count=0
    for l in calendar[i]:
        print("        ", str(count)+":",l)
        count+=1

输出:

2017-05-06:
     0: Sid's birthday
2017-02-12:
     0: Eye doctor
     1: lunch with sid
     2: dinner with Jane
2017-03-29:
     0: Change oil in blue car
     1: Fix tree near front walkway
     2: Get salad stuff