-7

If i wanted a list that contains numbers and words, like this one

random_list=["h: 100", "g: 57", "k: 1", "p: 200"]

Sorted numerically so it becomes

["k: 1", "g: 57", "h: 100", "p: 200"]

What would be the code in python 3?

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
hello
  • 11
  • 2

2 Answers2

4

Python sorting allows for a key keyword that can be used to define your own sorting method. The below code is for Python 2.7, I assume 3 is similar:

random_list=["h: 100", "g: 57", "k: 1", "p: 200"]

sorted(random_list, key=lambda x: int(x.split()[1]))

#  ['k: 1', 'g: 57', 'h: 100', 'p: 200']
tom10
  • 67,082
  • 10
  • 127
  • 137
2

Firstly, that's a wrong data structure. You either mean a list or a dictionary.

Since the contents of your 'list' are key-value pairs, I'm guessing what you need is a dictionary instead. Dictionaries have the sorted() function available to them.

Ladmerc
  • 1,158
  • 11
  • 18