Python - 一个dict可以有一个列表的值吗? [英] Python - can a dict have a value that is a list?

查看:109
本文介绍了Python - 一个dict可以有一个列表的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用Python时,dict可能有一个值列表?



例如,一个字典如下所示(请参阅KeyName3值):

  {
keyName1:value1,
keyName2:value2,
keyName3: {val1,val2,val3}
}

我已经知道我可以使用'defaultdict 然而,单个值(可理解地)作为列表返回。



我问的原因是我的代码必须是通用的,以便调用者可以将单键值作为项目(就像从一个dict键值)而不是列表(而不必指定 pop [0] 列表) - 但是也检索多个值作为列表。



如果没有,那么任何讽刺都是欢迎的。



如果有人可以帮助那么那将是伟大的。 / p>

感谢提前,



Paul



*我正在使用Python 2.6编写必须的脚本所以要向前兼容Python 3.0 +。

解决方案

是的。 dict中的值可以是任何类型的python对象。密钥可以是任何可哈希的对象(不允许列表,但允许一个元组)。



您需要使用 [] ,而不是 {} 创建列表:

  {keyName1:value1,keyName2:value2,keyName3:[val1,val2,val3]} 


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+.

解决方案

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:

{ keyName1 : value1, keyName2: value2, keyName3: [val1, val2, val3] }

这篇关于Python - 一个dict可以有一个列表的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆