Reputation: 13
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)
Upvotes: 1
Views: 105
Reputation: 3954
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}
Upvotes: 2