如果list是python词典的键对的值,则检索列表

时间:2017-12-01 00:47:32

标签: python python-3.x dictionary

我正在使用python 3.xxx

我在字典中保存了一整套字符串..

dict = { 'somekey' = '['one','two','three'...]......... *to n*}

现在,如果我知道key = 'somekey',我该如何检索值,整个列表。我试过了

dict.get(key,0) 

但它没有用。

1 个答案:

答案 0 :(得分:0)

首先,避免使用python关键字作为变量名,这导致shadowing导致很难找到错误。

要从字典中获取值,只需使用键索引字典。

>>> dct = {'foo': [1, 2, 3, 4], 'bar': [6, 7, 8]}
>>> dct['foo']
[1, 2, 3, 4]

同样的原则适用于默认的dicts。请记住正确实例化默认字典。

>>> from collections import defaultdict as ddict
>>> dct2 = ddct(list)
>>> dct2['foo'] = [1, 2, 3]
>>> dct2['bar'] = [3, 4, 5]
>>> dct2
defaultdict(<class 'list'>, {'foo': [1, 2, 3], 'bar': [3, 4, 5]})
>>> dct2['foo']
[1, 2, 3]

这会处理列表,包括混合类型列表:

>>> dct['qux'] = "You're welcome Taha".split()
>>> dct['xer'] = ['a', 1, 'c']
>>> dct['qux']
["You're", 'welcome', 'Taha']
>>> dct['xer']
['a', 1, 'c']
相关问题