[英]How can I extract data from a dictionary by specifying a range of values?
我有一本字典,
{"apple" : "20", "orange" : "40", "banana" : "25", "mango" : "50"}
我想從這個字典中提取數據,其值在20 - 30范圍內。
例。 我想輸出應該是
apple:20
banana:25
我正在考慮首先按值排序字典,但它似乎不起作用。
我試過dict= sorted(dict.items(), key=lambda t: t[1])
但輸出顯示如下:
[("apple", "20"), ("orange" , "40"), ("banana" , "25"), ("mango" , "50")]
我怎樣才能得到輸出:
apple:20
banana:25
sample_dict={"apple" : "20", "orange" : "40", "banana" : "25", "mango" : "50"}
for name,num in sample_dict.items():
if int(num) in range(20,31):
print('%s: %s' %(name,num))
d = {"apple" : "20", "orange" : "40", "banana" : "25", "mango" : "50"}
for k, v in d.items():
if 20 <= int(v) <= 30:
print(k, ':', v, sep='')
版畫
apple:20
banana:25
通過使用列表推導,您可以提取(key,values)
它們的值(首次轉換為int
)在20-30范圍內:
d = {"apple" : "20", "orange" : "40", "banana" : "25", "mango" : "50"}
[(k,v) for k,v in d.items() if 20 <= int(v) <= 30]
# [('banana', '25'), ('apple', '20')]
然后你可以得到你想要的輸出。
返回一個字典{'apple': '20', 'banana': '25'}
>>> d = {"apple" : "20", "orange" : "40", "banana" : "25", "mango" : "50"}
>>> {key: val for key,val in d.items() if 20 <= int(val) <= 30}
{'apple': '20', 'banana': '25'}
使用字典理解:
the_dict = {"apple" : "20", "orange" : "40", "banana" : "25", "mango" : "50"}
new_dict = {the_dict.keys()[i]:the_dict.values()[i] for i in range(len(the_dict.values())) if int(the_dict.values()[i]) <= 30 and int(the_dict.values()[i] >= 20)}
print new_dict
您可以使用一set
來獲得快速成員資格測試。 這樣做也消除了將字典的值轉換為整數的需要,因為set
的成員是字符串:
d = {"apple": "20", "orange": "40", "banana": "25", "mango": "50"}
limits = set(str(n) for n in range(20, 31))
for key, value in sorted(d.items()):
if value in limits:
print('{}:{}'.format(key, value))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.