Python 如何在字典中输出列表的索引号?
我有一个字典,其中包含一个列表,其中包含多个值,我应该有一个show方法以这种格式输出字典Python 如何在字典中输出列表的索引号?,python,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 b
"
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)
提前谢谢
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')
迭代每个日期的嵌套dict:
for l in calendar[key]:
list(calendar[key].keys())
列出每个日期的嵌套dict键:
for l in calendar[key]:
list(calendar[key].keys())
获取键的索引:
str(list(calendar[key].keys()).index(l))
您可以尝试以下方法:
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
不要只是脱口而出代码!添加一些文本来描述此代码如何最好地回答问题,这将提高答案的长期质量,并有助于防止在审阅过程中将其删除。@NightOwl888:已添加。谢谢,谢谢,这个方法很有效!非常感谢,您是否知道如何将此输出封装到str中,我刚刚意识到它需要采用这种格式。我已经编辑了上面的实际输出格式。