如何将键值对插入到 python 列表中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22496596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does one insert a key value pair into a python list?
提问by mango
a = 1
b = 2
i want to insert a:b into a blank python list
我想将 a:b 插入到一个空白的 python 列表中
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
这只是为了以后我可以按值从最小到最大对列表进行排序
采纳答案by dwurf
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]
回答by Christian
How does one insert a key value pair into a python list?
如何将键值对插入到 python 列表中?
You can't. What you can do is "imitate" this by appending tuples of 2 elements to the list:
你不能。您可以做的是通过将 2 个元素的元组附加到列表来“模仿”这一点:
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, ...
- 在使用字典之前,您应该阅读 Python 文档、一些教程或书籍,以便了解完整的概念。
- 不要将您的列表称为
list,因为它会隐藏其内置实现。将其命名为其他名称,例如some_list,L, ...

