from collections import OrderedDict
from collections import OrderedDict
OrderedDict就是一个类 需要需用 先进行 实例化
od = OrderedDict()然后和字典的用法是一样的
from collections import OrderedDictod = OrderedDict()od['k1'] = 'v1'od['k2'] = 'v2'od['k3'] = 'v3'for k, v in od.items(): print('k={},v={}'.format(k, v))
显示的结果就是
k=k1,v=v1 k=k2,v=v2 k=k3,v=v3
这就是有序字典了 有序字典就是按照插入数据的顺序输出的我的应用场景 是对一级菜单排序
from collections import OrderedDict @register.inclusion_tag('menu.html') def menu(request): od = OrderedDict() menu_dict = request.session.get(settings.MENU_SESSION_KEY) # url = request.path_info # for i in menu_list: # if re.match(r'{}$'.format(i['url']), url): # i['class'] = 'active' # break # print(menu_dict.values()) menu_list = sorted(menu_dict, key=lambda x: menu_dict[x]['weight'], reverse=True) # print(menu_list) for key in menu_list: od[key] = menu_dict[key] return {'menu_list': od.values()}