Search code examples
pythondefaultdict

Extract information from defaultdict


I have a defaultdict that contains the calculation of the average position of number ( Euler problem )

[('1', 0.6923076923076923), ('0', 2.0), ('3', 0.2222222222222222),
 ('2', 1.0909090909090908), ('7', 0.0), ('6', 0.875), 
('9', 1.6923076923076923),('8', 1.3333333333333333)]

I'm trying to get this information into simple string instead of doing it manually from 0 - 2. The end result I'm looking for is something like

73162890

I don't know any good way to extracting them without using many if-else and for-loops.

Is there any simple and good way of doing this in python?


Solution

  • If your dict is d, then items = d.items() gives you a list of pairs, like you have. Once you have this list, you can sort it by the second element:

    ordered = sorted(items, key=lambda (_, value): value) # Not Python 3
    
    # or,
    ordered = sorted(items, key=lambda x: x[1])
    
    # or,
    import operator
    ordered = sorted(items, key=operator.itemgetter(1))
    

    Once we have the list in sorted order, we just need to extract the strings from each one, and glue them all together:

    result = ''.join(string for (string, _) in ordered)
    

    (Note that I'm calling unused parameters _, there's nothing special about the _ in a Python program.)