Python--根据键对字典排序

方法一,zip函数

>>> dic = {"name":"zs","sex":"man","city":"beijing"}

#1. 字典转列表嵌套元组
>>> foo = zip(dic.keys(),dic.values())
>>> foo = [i for i in foo]
>>> print("字典转成列表嵌套元组",foo)
字典转成列表嵌套元组 [('name', 'zs'), ('sex', 'man'), ('city', 'beijing')]

#2. 字典嵌套元组排序
>>> b = sorted(foo,key=lambda x:x[0])
>>> print("根据键排序",b)
根据键排序 [('city', 'beijing'), ('name', 'zs'), ('sex', 'man')]

#3. 排序完构造新字典
>>> new_dic = {i[0]:i[1] for i in b}
>>> print("字典推导式构造新字典",new_dic)
字典推导式构造新字典 {'city': 'beijing', 'name': 'zs', 'sex': 'man'}
>>> 

方法二,不用zip
有没有发现dic.items和zip(dic.keys(),dic.values())都是为了构造列表嵌套字典的结构,方便后面用sorted()构造排序规则

>>> dic = {"name":"zs","sex":"man","city":"beijing"}
>>> print("字典转成列表嵌套元组",foo)
字典转成列表嵌套元组 [('name', 'zs'), ('sex', 'man'), ('city', 'beijing')]
>>> print(dic.items())
dict_items([('name', 'zs'), ('sex', 'man'), ('city', 'beijing')])
>>> b = sorted(dic.items(),key=lambda x:x[0])
>>> print("根据键排序",b)
SyntaxError: invalid character in identifier
>>> print("根据键排序",b)
根据键排序 [('city', 'beijing'), ('name', 'zs'), ('sex', 'man')]
>>> new_dic = {i[0]:i[1] for i in b}
>>> print("字典推导式构造新字典",new_dic)
字典推导式构造新字典 {'city': 'beijing', 'name': 'zs', 'sex': 'man'}
>>> 

 

你可能感兴趣的:(Python学习笔记)