How do I extract the keys of a dictionary based on a conditional?

Question:

I am asked to extract the dates of dictionary in which the values exceed the input threshold.

See code beneath:

def get_dates(prices,threshold):
    {k:v for  k,v  in prices  if threshold>130}
    

prc = [
    { 'price': 1279.79, 'date': '2020-01-01' },
    { 'price': 139.01, 'date': '2020-01-02' },
    { 'price': 134.3, 'date': '2020-01-03' },
    { 'price': 120.99, 'date': '2020-01-04' }
]

get_dates(prc, 130.0)

Ideally, the function should return the respective date on which the price is beyond the threshold (130). My code does not however return anything.

Asked By: Kash

||

Answers:

You can use list comprehensions and return dicts if the price is larger than the threshold.

Why dict.get(key) instead of dict[key]?

# we use 'dict.get' with default value '0' for price if don't exists.
def get_dates(prices,threshold):
    return [dct['date'] for dct in prices if dct.get('price', 0) > threshold]
            

prc = [
    { 'price': 1279.79, 'date': '2020-01-01' },
    { 'price': 139.01, 'date': '2020-01-02' },
    { 'price': 134.3, 'date': '2020-01-03' },
    { 'price': 120.99, 'date': '2020-01-04' }
]

get_dates(prc, 130.0)

Output:

['2020-01-01', '2020-01-02', '2020-01-03']
Answered By: I'mahdi

To return the dates you want, use a list comprehension that gets the date key from each dict where price is above threshold:

def get_dates(prices,threshold):
    return [d['date'] for d in prices if d['price'] > threshold]

prc = [
    { 'price': 1279.79, 'date': '2020-01-01' },
    { 'price': 139.01, 'date': '2020-01-02' },
    { 'price': 134.3, 'date': '2020-01-03' },
    { 'price': 120.99, 'date': '2020-01-04' }
]

print(get_dates(prc, 130.0))  # ['2020-01-01', '2020-01-02', '2020-01-03']
Answered By: Samwise

First of all there is no return keyword in your function.
Then do it like this

def get_dates(prices, threshold) :
    dates=[]
    for dict in prices:
        if dict['price']>threshold:
            dates.append(dict['date'])
    return dates

This will return an array of dates
Then to get this array use
dates=get_dates(prc, 130)

Answered By: Dante
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.