Find min Python

2992 views python
5

I want the code to execute which in return will give me the minimum value among the following but greater than 0.5

I have also attached the error I am getting

mydict = {'fruits': [0, 'apple', 'orange'],
 'vegetables': [1, 'carrot'], 
 'cheese': [2, 'cheddar', 'brie']}
l=[]
i=0

for j in mydict.values():
if(0.5 <= j[0]):
    l[i]=j[0]
    i=i+1

min(l)

answered question

Can you please edit the error into the question, rather than an image. Thank you

3 Answers

9

You need to append values instead of assigning them

mydict = {'fruits': [0, 'apple', 'orange'],
 'vegetables': [1, 'carrot'], 
 'cheese': [2, 'cheddar', 'brie']}
l=[]

for j in mydict.values():
  if(0.5 <= j[0]):
    l.append(j[0]) # append adds a new element to the list

min(l)

posted this
8

You can do this with a list comprehension

mydict = {
    'fruits': [0, 'apple', 'orange'],
    'vegetables': [1, 'carrot'], 
    'cheese': [2, 'cheddar', 'brie']
}

min([i[0] for i in mydict.values() if i[0] >= 0.5])

posted this
12

food = {
    'fruits': [0, 'apple', 'orange'],
    'vegetables': [1, 'carrot'],
    'cheese': [2, 'cheddar', 'brie'],
}

min_list = []

for i in food.values():
    if i[0] >= .5:
        min_list.append(i[0])

print(min(min_list))

Output :

(xenial)vash@localhost:~/python/stack_overflow$ python3.7 min.py
1

posted this

Have an answer?

JD

Please login first before posting an answer.