How does one insert a key value pair into a python list?
How does one insert a key value pair into a python list?
You can't. What you can do is "imitate" this by appending tuples of 2 elements to the list:
a = 1
b = 2
some_list = []
some_list.append((a, b))
some_list.append((3, 4))
print some_list
>>> [(1, 2), (3, 4)]
But the correct/best way would be using a dictionary:
some_dict = {}
some_dict[a] = b
some_dict[3] = 4
print some_dict
>>> {1: 2, 3: 4}
Note:
- Before using a dictionary you should read the Python documentation, some tutorial or some book, so you get the full concept.
- Don't call your list as
list
, because it will hide its built-in implementation. Name it something else, likesome_list
,L
, ...
Let's assume your data looks like this:
a: 15
c: 10
b: 2
There are several ways to have your data sorted. This key/value data is best stored as a dictionary, like so:
data = {
'a': 15,
'c': 10,
'b': 2,
}
# Sort by key:
print [v for (k, v) in sorted(data.iteritems())]
# Output: [15, 2, 10]
# Keys, sorted by value:
from operator import itemgetter
print [k for (k, v) in sorted(data.iteritems(), key = itemgetter(1))]
# Output: ['b', 'c', 'a']
If you store the data as a list of tuples:
data = [
('a', 15),
('c', 10),
('b', 2),
]
data.sort() # Sorts the list in-place
print data
# Output: [('a', 15), ('b', 2), ('c', 10)]
print [x[1] for x in data]
# Output [15, 2, 10]
# Sort by value:
from operator import itemgetter
data = sorted(data, key = itemgetter(1))
print data
# Output [('b', 2), ('c', 10), ('a', 15)]
print [x[1] for x in data]
# Output [2, 10, 15]