简体   繁体   中英

Return key/value from a dictionary less than or equal to a limit

I am trying to create a program that gathers the values from a dictionary that are less than or equal to an entered value. The desired return will be a specific list that has the key,value in it. I am not sure how to begin or write this program.

For example:

dictionary1 = {'drill': 250.89, 'hammer': 25.99, 'press': 365.33}
Upper limit: 165

I will need to get a list back of all the contents of the dictionary and put them into a list, that have the value less than or equal to 165. The returned list in this case should be: list1 = ['hammer', 25.99]

Any help is greatly appreciated

Use alist comprehension to filter the key/value pairs:

upper_limit = 165
dictionary1 = {'drill': 250.89, 'hammer': 25.99, 'press': 365.33}

res = [(tool, value) for tool, value in dictionary1.items() if value < upper_limit]
print(res)

Output

[('hammer', 25.99)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM