Question

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?

Was it helpful?

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.)

OTHER TIPS

In [36]: ''.join([key for key, val in sorted(data, key = lambda item: item[1])])
Out[36]: '73162890'

Explanation:

This sorts the data according to the second value for each item in data.

In [37]: sorted(data, key = lambda item: item[1])
Out[37]: 
[('7', 0.0),
 ('3', 0.2222222222222222),
 ('1', 0.6923076923076923),
 ('6', 0.875),
 ('2', 1.0909090909090908),
 ('8', 1.3333333333333333),
 ('9', 1.6923076923076923),
 ('0', 2.0)]

Now we can collect the first value in each item using a list comprehension:

In [38]: [key for key, val in sorted(data, key = lambda item: item[1])]
Out[38]: ['7', '3', '1', '6', '2', '8', '9', '0']

And join these items into a string using ''.join:

In [39]: ''.join([key for key, val in sorted(data, key = lambda item: item[1])])
Out[39]: '73162890'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top