Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one insert a key value pair into a python list?

Tags:

python

list

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

like image 394
mango Avatar asked Mar 19 '14 04:03

mango


People also ask

How do I add a key-value pair to a list in Python?

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.

How do you add a key-value pair to a list?

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().

How do you represent a key-value in Python?

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 {}.


Video Answer


1 Answers

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]
like image 52
dwurf Avatar answered Oct 22 '22 21:10

dwurf