Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Lọc giá trị âm khỏi dictionary trong Python


Khi phân tích dữ liệu, cần loại bỏ các cặp khóa-giá trị có giá trị âm trong dictionary. Hai cách tiếp cận.

Dùng vòng lặp for

Duyệt items(), giữ lại cặp có giá trị >= 0.

Ví dụ

dict_1 = {'x':10, 'y':20, 'z':-30, 'p':-0.5, 'q':50} 
print ("Given Dictionary :", str(dict_1)) 
final_res_1 = dict((i, j) for i, j in dict_1.items() if j >= 0) 
print("After filtering the negative values from dictionary : ", str(final_res_1))

Đầu ra

Given Dictionary : {'x': 10, 'y': 20, 'z': -30, 'p': -0.5, 'q': 50} 
After filtering the negative values from dictionary : {'x': 10, 'y': 20, 'q': 50}

Dùng hàm lambda

Sử dụng filter với lambda để cú pháp gọn hơn.

Ví dụ

dictA = {'x':-4/2, 'y':15, 'z':-7.5, 'p':-9, 'q':17.2} 
print ("\nGiven Dictionary :", dictA) 
final_res = dict(filter(lambda k: k[1] >= 0.0, dictA.items())) 
print("After filtering the negative values from dictionary : ", str(final_res))

Đầu ra

Given Dictionary : {'x': -2.0, 'y': 15, 'z': -7.5, 'p': -9, 'q': 17.2} 
After filtering the negative values from dictionary : {'y': 15, 'q': 17.2}