Disordered and ordered dictionary dictionary

Because it uses in the project looked at

 

 python3.5 dictionary are unordered

from collections import OrderedDict

python3.6 only show is actually ordered but chaotic

After python3.7 dictionary is ordered

 

Ordered dictionary should first import

from collections import OrderedDict
OrderedDict is a required class needs to be instantiated
od = OrderedDict () 
and then use the dictionary and is the same
Copy the code
from collections import OrderedDict

od = OrderedDict()
od['k1'] = 'v1'
od['k2'] = 'v2'
od['k3'] = 'v3'
for k, v in od.items():
print('k={},v={}'.format(k, v))
Copy the code

The result is displayed

k1 = the k, v = v1 
the k = k2, v = v2 
the k = k3, v = v3

This is a dictionary ordered ordered dictionary is inserted into the output data in the order of


my application scenario is sort of a menu

Copy the code
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()}

Guess you like

Origin www.cnblogs.com/lzlllll/p/11247175.html