a = 1
b = 2
i want to insert a:b into a blank python list
list = []
as
a:b
what is the proper syntax for this, to result in
[(a:b), (c:d)]
?
this is just so I can sort the list by value from least to greatest later
Using the update() method The update method directly takes a key-value pair and puts it into the existing dictionary. The key value pair is the argument to the update function. We can also supply multiple key values as shown below.
Another approach we can take to add a key-value pair in the list is to setNames() function and inside it, we use as. list().
Python's efficient key/value hash table structure is called a "dict". The contents of a dict can be written as a series of key:value pairs within braces { }, e.g. dict = {key1:value1, key2:value2, ... }. The "empty dict" is just an empty pair of curly braces {}.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With