我最近一直在使用字典,我一直致力于一个项目,其中包括将一天的活动保存到日历中。
因此密钥的格式为日期格式yyyy-mm-dd。我希望这样做,以便字典中的每个“键”都可以根据日期而出现。例如:关键的2015-11-10以及当天的活动和2015-11-9的活动,我希望2015-11-9及其活动首先打印出来。我已经尝试过排序和元组等。但是这只会对密钥内部的内容进行排序而不是密钥本身。有什么想法或建议吗?
>>> calendar = {}
>>> command_add("2015-10-12", "Eye doctor", calendar)
''
>>> command_add("2015-10-12", "lunch with sid", calendar)
''
>>> command_add("2015-10-29", "Change oil in blue car", calendar)
''
>>> command_add("2015-10-12", "dinner with Jane", calendar)
''
>>> command_add("2015-10-29", "Fix tree near front walkway", calendar)
''
>>> command_add("2015-10-29", "Get salad stuff", calendar)
''
>>> command_add("2015-11-06", "Sid's birthday", calendar)
''
>>> command_show(calendar)
我需要的是:
>>> command_show(calendar)
2015-10-12:
0: Eye doctor
1: lunch with sid
2: dinner with Jane
2015-10-29:
0: Change oil in blue car
1: Fix tree near front walkway
2: Get salad stuff
2015-11-06:
0: Sid's birthday
''
答案 0 :(得分:1)
正常dictionaries是无序的。如果您需要有序字典,则必须使用OrderedDict
。
但我想以有序的方式迭代值就足够了。通常,你这样做:
for key, value in sorted(mydict.items()):
pass # now it is sorted in ascending order of key
请注意,mydict
仍然无序。 .items()
返回(key, value)
元组列表。列表可以排序。
#!/usr/bin/env python
def command_add(day, event_name, calendar):
if day in calendar:
calendar[day].append(event_name)
else:
calendar[day] = [event_name]
def command_show(calendar):
"""
Parameters
----------
calendar : dict
The keys are dates in the format YYYY-MM-DD and the values are lists
of events
"""
for day, events in sorted(calendar.items()):
print("%s:" % day)
for i, event in enumerate(events):
print("\t%i: %s" % (i, event))
calendar = {}
command_add("2015-10-12", "Eye doctor", calendar)
command_add("2015-10-12", "lunch with sid", calendar)
command_add("2015-10-29", "Change oil in blue car", calendar)
command_add("2015-10-12", "dinner with Jane", calendar)
command_add("2015-10-29", "Fix tree near front walkway", calendar)
command_add("2015-10-29", "Get salad stuff", calendar)
command_add("2015-11-06", "Sid's birthday", calendar)
command_show(calendar)