If I have this:
[(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
How can I separate the integer from the string and then sort it to get this result:
0 'my'
1 'cat'
2 'ate'
3 'it'
If I have this:
[(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
How can I separate the integer from the string and then sort it to get this result:
0 'my'
1 'cat'
2 'ate'
3 'it'
Try this:
x = sorted([(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')])
for i in x:
print(i)
output:
(0, 'my')
(1, 'cat')
(2, 'ate')
(3, 'it')
Pythonic way, how sorting, itemgetter
from documentation: "return a callable object that fetches item"
L = [(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
from operator import itemgetter
print ( "\n".join(map(lambda x: "%d '%s'" % x, sorted(L, key=itemgetter(0)))))
you get,
0 'my'
1 'cat'
2 'ate'
3 'it'
Simply sort the list of tuples, and the print them formatted:
>>> tuples = [(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
>>> tuples = sorted(tuples)
>>> for tup in tuples:
print("{} '{}'".format(*tup))
0 'my'
1 'cat'
2 'ate'
3 'it'
>>>
Try the following:
l = [(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
for item in sorted(l):
print("{} '{}'".format(item[0], item[1]))
Output:
0 'my'
1 'cat'
2 'ate'
3 'it'
I found an answer to your question on ... How can I sort a dictionary by key?
Using that code, I developed the following:
#!/usr/bin/python3
# StackOverflow answer sample to question:
# How to separate and sort a list of integers and it's associated string?
# Author: RJC (aka mmaurice)
# Question input: [(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
# Question expected output:
# 0 'my'
#
# 1 'cat'
#
# 2 'ate'
#
# 3 'it'
import collections
test_dict = dict([(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')])
print(test_dict) #not in order
#use collections to sort the dictionary.
od_test_dict = collections.OrderedDict(sorted(test_dict.items()))
for k, v in od_test_dict.items(): print(k, v)
Hope this helps