Dictionaries dict Sort : Assign according to key Sort or values Sort .
For dictionaries or list Remove duplicate elements .
Tips : Get ready
dicta ={
'a':1,'b':2,'d':7,'c':23,'m':21,'f':4}
1、 Dictionaries dict Press key Sort , In ascending or descending order
According to the dictionary key Sort :
dicta_sorted = sorted(dicta.items(),key=lambda x :x[0])
print(dicta_sorted)
Output results :
[('a', 1), ('b', 2), ('c', 23), ('d', 7), ('f', 4), ('m', 21)]
Default ascending order , If you want to go down , be :
dicta_sorted = sorted(dicta.items(),key=lambda x :x[0],reverse=True)
print(dicta_sorted)
Output results :
[('m', 21), ('f', 4), ('d', 7), ('c', 23), ('b', 2), ('a', 1)]
2、 Dictionaries dict Press values Sort , In ascending or descending order
Ascending
dicta_sorted = sorted(dicta.items(),key=lambda x :x[1])
print(dicta_sorted)
result :
[('a', 1), ('b', 2), ('f', 4), ('d', 7), ('m', 21), ('c', 23)]
Descending :
dicta_sorted = sorted(dicta.items(),key=lambda x :x[1],reverse=True)
print(dicta_sorted)
result :
[('c', 23), ('m', 21), ('d', 7), ('f', 4), ('b', 2), ('a', 1)]
3、 To the dictionary dict perhaps list Medium to heavy , Output the number of duplicates removed
Out-of-service for Loop through the judgment one by one values Whether to repeat , Too time consuming , make the best of dict Find data and set The characteristics of de duplication .
def find_unique_price_using_set(products):
unique_price_set = set()
for _, price in products:
unique_price_set.add(price)
return len(unique_price_set)
products = [
(143121312, 100),
(432314553, 30),
(32421912367, 150),
(937153201, 30)
]
print('number of unique price is: {}'.format(find_unique_price_using_set(products)))
# Output number of unique price is: 3
perhaps
def find_unique_price_using_set_dict(products):
dist_products=dict(products)
set_price=set(dist_products.values())
return len(set_price)
products = [
(143121312, 100),
(432314553, 30),
(32421912367, 150),
(937153201, 30)
]
import time
# Computing sets _ The time of the dictionary version
start_using_set = time.perf_counter()
find_unique_price_using_set_dict(products)
end_using_set = time.perf_counter()
print("time elapse using set_dict: {}".format(end_using_set - start_using_set))
The two methods are similar , The running time is very short , The weight removal efficiency is very high . For 10000 data, only 0.0123 second
4、 Master the loop sentence
theory 10 minute , Time 30 minute
master :
1、 Dictionaries dict Sort , It can be specified according to key Sort , You can also follow values Sort .
2、 aggregate set Deduplication .