Print the sorted city names by an integer from a textfile

Viewed 87

I have a textfile that has a city and a number on each line like this:

city1 15
city2 25
city3 2
city4 8
city5 10

I want to print the cities in order from the lowest number to the hights

The print should look like:

city3, city4, city5, city1, city2  

Tried this:

lst = []
with open('livrari.txt', mode='r') as my_file:
    for line in my_file:
       lst.append(line.strip())
lst.sort()

print(lst)

This gives me a list of lists containing the city and the number. Can someone help me finish this?

4 Answers
cities = """city1 15
city2 25
city3 2
city4 8
city5 10"""

d = {}
for city_row in cities.splitlines():
    city, num = city_row.split(' ')
    d[int(num)] = city

d = dict(sorted(d.items())) # Sort

print([d[k] for k in d])

->

['city3', 'city4', 'city5', 'city1', 'city2']

You're almost there. All you need is to tell the list sorting to make use of a particular value within the tuple for the sort, since a general sort would go over each element within the tuple to sort them.

Since we're looking at the second element of the tuple i.e. the number field, we'll sort using that, in the following way:

lst = []
with open('livrari.txt', mode='r') as my_file:
    for line in my_file:
        city, number = line.strip().split(' ')
        # Note that the number field needs to be converted to an integer since
        # having them on string would not reap you the numeric sort
        number = int(number)
        lst.append((city, number))
# The key argument to the sort method is used to tell the list sort to pick a particular field for sorting in terms of nested structures like this one.
lst.sort(key=lambda x: x[1])

print(lst)
[('city3', 2), ('city4', 8), ('city5', 10), ('city1', 15), ('city2', 25)]

Here are minimal changes to your code to make it work:

Try it online!

lst = []
with open('livrari.txt', mode='r') as my_file:
    for line in my_file:
       lst.append(line.split())
lst.sort(key = lambda e: int(e[1]))
print(', '.join([e[0] for e in lst]))

Output:

city3, city4, city5, city1, city2

For input:

city1 15
city2 25
city3 2
city4 8
city5 10

You can use a lambda that sorts your data based on the number in the second column.

with open('csvfile1.csv') as input:
    reader = csv.reader(input, delimiter = " ")
    sortedlist = sorted(reader, key=lambda col: int(col[1]), reverse=False)
print(", ".join([lst[0] for lst in sortedlist]))
# city3, city4, city5, city1, city2
Related