Lorientas
Lorientas

Reputation: 66

Using dictionaries in loop

I am trying to write a code that replicates greedy algorithm and for that I need to make sure that my calculations use the highest value possible. Potential values are presented in a dictionary and my goal is to use largest value first and then move on to lower values. However since dictionary values are not sequenced, in for loop I am getting unorganized sequences. For example, out put of below code would start from 25.

How can I make sure that my code is using a dictionary yet following the sequence of (500,100,25,10,5)?

a={"f":500,"o":100,"q":25,"d":10,"n":5}  
for i in a:
    print a[i]

Upvotes: 1

Views: 117

Answers (4)

LexyStardust
LexyStardust

Reputation: 1018

Dictionaries yield their keys when you iterate them normally, but you can use the items() view to get tuples of the key and value. That'll be un-ordered, but you can then use sorted() on the "one-th" element of the tuples (the value) with reverse set to True:

a={"f":500,"o":100,"q":25,"d":10,"n":5}  
for k, v in sorted(a.items(), key=operator.itemgetter(1), reverse=True):
    print(v)

I'm guessing that you do actually need the keys, but if not, you can just use values() instead of items(): sorted(a.values(), reverse=True)

Upvotes: 3

chandu
chandu

Reputation: 1063

You can use this

>>> a={"f":500,"o":100,"q":25,"d":10,"n":5}
>>> for value in sorted(a.itervalues(),reverse=True):
...     print value
... 
500
100
25
10
5
>>> 

Upvotes: 1

Joe T. Boka
Joe T. Boka

Reputation: 6585

a={"f":500,"o":100,"q":25,"d":10,"n":5}
k = sorted(a, key=a.__getitem__, reverse=True)
v = sorted(a.values(), reverse=True)
sorted_a = zip(k,v)
print (sorted_a)

Output:

[('f', 500), ('o', 100), ('q', 25), ('d', 10), ('n', 5)]

Upvotes: -1

alexwlchan
alexwlchan

Reputation: 6098

Two ideas spring to mind:

  1. Use collections.OrderedDict, a dictionary subclass which remembers the order in which items are added. As long as you add the pairs in descending value order, looping over this dict will return them in the right order.

  2. If you can't be sure the items will be added to the dict in the right order, you could construct them by sorting:

    • Get the values of the dictionary with values()
    • Sort by (ascending) value: this is sorted(), and Python will default to sorting in ascending order
    • Get them by descending value instead: this is reverse=True

    Here's an example:

    for value in sorted(a.values(), reverse=True):
        print value
    

Upvotes: 3

Related Questions