字典去重与排序

l=[
    {'name':'egon','age':18,'sex':'male'},
    {'name':'alex','age':73,'sex':'male'},
    {'name':'egon','age':20,'sex':'female'},
    {'name':'egon','age':18,'sex':'male'},
    {'name':'egon','age':18,'sex':'male'},
]
#1
s=set()
l1=[]
for item in l:
    val=(item['name'],item['age'],item['sex'])
    if val not in s:
        s.add(val)
        print(s)
        l1.append(item)
print(l1)



#2
def func(items,key=None):
    s=set()
    for item in items:
        val=item if key is None else key(item)
        if val not in s:
            s.add(val)
            yield item

print(list(func(l,key=lambda dic:(dic['name'],dic['age'],dic['sex']))))


#3
l1=[]
for i in l:
    if i not in l1:
        l1.append(i)
print(l1)




salary_dict = {
    'nick': 3000,
    'jason': 100000,
    'tank': 5000,
    'sean': 2000
}
salary_list = list(salary_dict.items())
print(salary_list)  # [('nick', 3000), ('jason', 100000), ('tank', 5000), ('sean', 2000)]


# def func(i):  # i = ('sean', 2000), ('nick', 3000),('tank', 5000),('jason', 100000)
#     return i[1]  # 2000,3000,5000,100000


salary_list.sort(key=lambda i: i[1])  # 内置方法是对原值排序
# # 按照func的规则取出一堆元素2000,3000,5000,100000
# # 然后按照取出的元素排序
print(salary_list)
#用字典的值对字典进行排序
import operator
x = {1:2,3:4,5:6,7:8}
sort_x = sorted(x.items(),key=operator.itemgetter(1))
print(sort_x)
# 字典是无序的不可能进行排序,只能转化成另一种方式进行排序,比如元组
posted @ 2019-08-26 15:56  豆瓣酱瓣豆  阅读(309)  评论(0编辑  收藏  举报