在字典列表上应用 dict() 返回了意外的值。 dict() 是如何工作的?
Applying dict() on list of dicts returned unexpected value. How dict() Works?
Python 3.8.6
我有一个具有相似键的字典列表。喜欢这个:
data = [
{
'type':
'individual', 'details': {}
},
{
'type': 'personal',
'details': {}
}
]
没想到 dict(data)
returned {'type': 'details'}
.
我认为这段代码应该 return 一个例外,但它没有。
那里发生了什么?
为什么 Python 假设这是正确的行为?
这种行为有什么有用的例子吗?
调用 dict() 的方法之一的模糊用法。
Otherwise, the positional argument must be an iterable object.
Each item in the iterable must itself be an iterable with exactly two
objects. The first object of each item becomes a key in the new
dictionary, and the second object the corresponding value. If a key
occurs more than once, the last value for that key becomes the
corresponding value in the new dictionary.
遍历字典给你它的键,所以无意中你的论点完全符合要求。
没有人会像您刚才那样给 dict()
打电话。调用 dict(enumerate(my_list))
是一个更有趣的用例。
Python 3.8.6
我有一个具有相似键的字典列表。喜欢这个:
data = [
{
'type':
'individual', 'details': {}
},
{
'type': 'personal',
'details': {}
}
]
没想到 dict(data)
returned {'type': 'details'}
.
我认为这段代码应该 return 一个例外,但它没有。
那里发生了什么?
为什么 Python 假设这是正确的行为?
这种行为有什么有用的例子吗?
调用 dict() 的方法之一的模糊用法。
Otherwise, the positional argument must be an iterable object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.
遍历字典给你它的键,所以无意中你的论点完全符合要求。
没有人会像您刚才那样给 dict()
打电话。调用 dict(enumerate(my_list))
是一个更有趣的用例。