Python - 字典可以有一个列表值吗?
使用Python时,字典是否可以有一个列表值?
例如,一个字典如下所示(请参阅 KeyName3 的值):
{
keyName1 : value1,
keyName2: value2,
keyName3: {val1, val2, val3}
}
我已经知道我可以使用“defaultdict”,但是单个值(可以理解)作为列表返回。
我问的原因是我的代码必须是通用的,以便调用者可以将单个键值作为项目(就像从字典键值中一样)而不是列表(无需指定 pop[0]< /code> 列表) - 但是也可以将多个值作为列表检索。
如果没有,那么欢迎提出任何建议。
如果有人可以提供帮助那就太好了。
预先感谢,
Paul
*我正在使用 Python 2.6,但是编写的脚本也必须与 Python 3.0+ 向前兼容。
When using Python is it possible that a dict can have a value that is a list?
for example, a dictionary that would look like the following (see KeyName3's values):
{
keyName1 : value1,
keyName2: value2,
keyName3: {val1, val2, val3}
}
I already know that I can use 'defaultdict' however single values are (understandably) returned as a list.
The reason I ask is that my code must be generic so that the caller can retieve single key values as an item (just like from a dict key-value) and not as list (without having to specify pop[0]
the list) - however also retrieve multiple values as a list.
If not then any suugestions would be welcome.
If someone can help then that would be great.
Thanks in Advance,
Paul
*I'm using Python 2.6 however writing scripts that must also be forward compatible with Python 3.0+.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的。字典中的值可以是任何类型的 python 对象。键可以是任何可散列对象(不允许使用列表,但允许使用元组)。
您需要使用
[]
而不是{}
来创建列表:Yes. The values in a dict can be any kind of python object. The keys can be any hashable object (which does not allow a list, but does allow a tuple).
You need to use
[]
, not{}
to create a list:是的,这是可能的:
输出:
Yes, it's possible:
output:
它肯定可以有一个列表和任何对象作为值,但字典不能有一个列表作为键,因为列表是可变的数据结构,键不能是可变的,否则它们有什么用。
It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.