如何将键值元组列表转换为字典? [英] How to convert list of key-value tuples into dictionary?
问题描述
我有一个如下所示的列表:
[('A', 1), ('B', 2), ('C', 3)]
我想把它变成一个看起来像这样的字典:
{'A': 1, 'B': 2, 'C': 3}
解决这个问题的最佳方法是什么?
我的元组列表实际上更像是:
[(A, 12937012397), (BERA, 2034927830), (CE, 2349057340)]
我收到错误 ValueError: dictionary update sequence element #0 has length 1916;2 是必需的
你的错误:
为什么会出现 ValueError: dictionary update sequence element #0 has length 1916;2 是必需的
错误:
答案是您列表中的元素并不是您认为的那样.如果您键入 myList[0]
,您会发现列表的第一个元素不是二元组,例如('A', 1)
,而是一个 1916 长度的可迭代对象.
一旦您实际上拥有您在原始问题中陈述的形式的列表 (myList = [('A',1),('B',2),...]
),你只需要dict(myList)
.
[2021 现在也回答实际提出的问题,而不是关于特定错误的预期问题:]
一般来说:
要么使用通常的 dict(iterableOrMapping)
构造函数,或使用dict理解 {someExpr(k,v) for k:v in iterable}
语法:
<预><代码>>>>{x:x**2 for x in range(3)}{0: 0, 1: 1, 2:4}
# inline;与示例 1 有效相同.可能是一个可迭代的,例如# 一个序列,评估生成器,生成器表达式>>>字典(拉链(范围(2),范围(2))){0: 0, 1: 1, 2:2}
Python 字典是一个 O(1) 可搜索的对 {(k
ey→v
alue), ...} 的无序集合,其中键是任何不可变对象,值是任何对象.
键必须实现 .__eq__()代码>
和 .__hash__()
字典中可用的方法.如果您正在考虑实现这一点,您可能做错了什么,应该考虑使用不同的映射数据结构!(尽管有时您可以将键包装在不同的包装结构中并使用常规字典,但这可能并不理想.)
希望实现冻结"或不可变"类型,或伪装成一个类型的中级或高级程序员必须非常小心暗示,否则您的程序将出错极其微妙和接近-无法找到的错误:
如果您允许自己稍后对对象进行变异以使其相等的概念可能会改变,则不能使用 dict.被视为相等的对象必须始终让 __eq__
返回 True 并且让 __hash__
返回相同的值.
方法必须完全遵守规范.这意味着:
- 对于新手:哈希函数(wikip.)让您获得误报或真阳性结果;
hash(x)==hash(y)
意味着x
可能等于y
并且内部 python 代码必须检查x==y
(.__eq__
) 来确认它是真阳性而不是假阳性.这允许 O(1) 查找. - 对于新手:一旦对象处于最终状态,
__hash__
值不会因任何原因而改变,这一点至关重要.如果您不能同时保证这一点并且hash(x)!=hash(y) 暗示 x!=y
,则您不应该使用字典. - 人们可能会考虑使用 不同类型的映射而不是修改数据本身.这可以等效于编写包装器对象,但代价是使用库.这通常不是必需的.
- 对于专家:还应该注意的是,某些默认对象的哈希值是加盐的,并且可能会在 Python 调用和版本之间发生变化(如果您以任何方式存储或网络通信包含 Python 哈希值的数据,这可能是一个问题;它们是应该在每次进程启动时重新生成的内部细节).
Python 有一堆内置的冻结数据结构,例如 namedtuple
、frozenset
等,但它们有时更难使用.tuple
是基本 list
结构的基本冻结变体(它可以让你存储一个 {(1, 2): 3, (4, 5):6}
).它还有一些 dict
结构的变体.如果你想从frozen dicts"中获取地图对于值,除了作为第三方库之外,frozendict 不存在,但是您可以将 dict 的 .items()
提取为 tuple 的无序
frozenset
s.
I have a list that looks like:
[('A', 1), ('B', 2), ('C', 3)]
I want to turn it into a dictionary that looks like:
{'A': 1, 'B': 2, 'C': 3}
What's the best way to go about this?
EDIT: My list of tuples is actually more like:
[(A, 12937012397), (BERA, 2034927830), (CE, 2349057340)]
I am getting the error ValueError: dictionary update sequence element #0 has length 1916; 2 is required
Your error:
Why you are getting the ValueError: dictionary update sequence element #0 has length 1916; 2 is required
error:
The answer is that the elements of your list are not what you think they are. If you type myList[0]
you will find that the first element of your list is not a two-tuple, e.g. ('A', 1)
, but rather a 1916-length iterable.
Once you actually have a list in the form you stated in your original question (myList = [('A',1),('B',2),...]
), all you need to do is dict(myList)
.
[2021 edit: now also answers the actual question asked, not the intended question about the specific error:]
In general:
Either use the usual dict(iterableOrMapping)
constructor, or use the dict comprehension {someExpr(k,v) for k:v in iterable}
syntax:
>>> example1 = [('A',1), ('B',2), ('C',3)]
>>> dict(example1)
{'A': 1, 'B': 2, 'C': 3}
>>> {x:x**2 for x in range(3)}
{0: 0, 1: 1, 2:4}
# inline; same as example 1 effectively. may be an iterable, such as
# a sequence, evaluated generator, generator expression
>>> dict( zip(range(2),range(2)) )
{0: 0, 1: 1, 2:2}
A Python dictionary is an O(1)-searchable unordered collection of pairs {(k
ey→v
alue), ...} where keys are any immutable objects and values are any object.
Keys MUST implement the .__eq__()
and .__hash__()
methods to be usable in the dictionary. If you are thinking of implementing this, you are likely doing something wrong and should maybe consider a different mapping data structure! (Though sometimes you can get away with wrapping the keys in a different wrapper structure and using a regular dict, this may not be ideal.)
Intermediate or advanced programmers who wish to implement a 'frozen' or 'immutable' type, or one which masquerades as one, must be very careful of implications or else your program will be wrong with extremely subtle and near-impossible-to-find bugs:
You can't use a dict if you allow yourself to mutate the object later such that its notion of equality might change. Objects considered equal must always have __eq__
return True and have __hash__
return identical values.
The methods must exactly obey the spec. This means that:
- For novices: Hash functions(wikip.) let you get a false-positive or true-positive result;
hash(x)==hash(y)
meansx
MIGHT equaly
and the internal python code must then checkx==y
(.__eq__
) to confirm it's a true-positive and not a false-positive. This allows O(1) lookup. - For novices: It is critically important that the
__hash__
value not change for any reason once the object is in its final state. If you cannot guarantee both this andhash(x)!=hash(y) implies x!=y
, you should not be using a dict. - One might consider a different type of mapping rather than modifying the data itself. This can be equivalent to writing a wrapper object, at the cost of using a library. This is usually not necessary.
- For experts: It should also be noted that the hashes of some default objects are salted and may change between python invocations and versions (this may be a gotcha if you store or network-communicate data in any way that contains python hashes; they are an internal detail that should be regenerated on each process startup).
Python has a bunch of built-in frozen datastructures such as namedtuple
, frozenset
, etc., but they are sometimes harder to work with. tuple
is the basic frozen variant of the basic list
structure (which would let you store a {(1, 2): 3, (4, 5): 6}
). It also has some variants of the dict
structure. If you want to get a map from "frozen dicts" to values, frozendict doesn't exist except as a third-party library, but you can extract the dict's .items()
as a an unordered frozenset
of tuple
s.
这篇关于如何将键值元组列表转换为字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!