1

I am trying to remove the element that have minimum value in the dictionary to try to arrange the rest to the ascending order;

dict={}
for line in file:
    line = line.split()
    dict.update({line[0]:line[1]})

while dict.items():
    min = float(100)
    for x in dict:
        print(dict[x])
        g=float(dict[x])
        if (g<min):
            min=float(dict[x])
    print(min)

for name, avg in dict.items():
    if float(avg) == min:
        print(name)

fileout.write(name+ '\t' + str(avg) + '\n')
del dict[name]
print(dict)
Yagiz Degirmenci
  • 16,595
  • 7
  • 65
  • 85
  • 2
    Consider using another name for ```min``` variable, ```min``` is a reserved word in python and referst to the function ```min()``` to calculate the ```minimum``` – EnriqueBet Jun 22 '20 at 15:39
  • 2
    btw Don't use variable names like `dict`. This is a built-in and this may cause problems in your code. – quamrana Jun 22 '20 at 15:39
  • After the loop, `name` is key of the last item in the dict, not the one with the minimum value. You need another variable to hold that. – Barmar Jun 22 '20 at 15:39
  • You found the minimum item in the dict - but all you did with it was print it; you didn't save that particular value of `name` for later use. – jasonharper Jun 22 '20 at 15:40
  • You don't need a loop to find the minimum value: `min_value = min(d.values())` – Barmar Jun 22 '20 at 15:40
  • Where is your code that tries to arrange the rest in ascending order? – Barmar Jun 22 '20 at 15:41

1 Answers1

2

It would be easier to build a new dictionary from the previous one. By using sorted, dict.items() and passing key as lambda i: i[1] we can build a sorted dictionary. Finally we want to get all bar the first value and so we need to slice the result of sorted

d = {'a': 3, 'b': 1, 'c': 2}
new_d = dict(sorted(d.items(), key=lambda i: i[1])[1:])
print(new_d)
# {'c': 2, 'a': 3}

If you have to mutate the first object then we can just clear and rebuild it with dict.update.

d = {'a': 3, 'b': 1, 'c': 2}
new_d = sorted(d.items(), key=lambda i: i[1])[1:]
d.clear()
d.update(new_d)
print(d)
# {'c': 2, 'a': 3}
Peilonrayz
  • 3,129
  • 1
  • 25
  • 37