如果list是python字典的密钥对的值,则检索list

2024-06-24 13:18:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python 3.xxx

我在字典里存了一整串字符串

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

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

dict.get(key,0) 

但它不起作用


Tags: tokey字符串列表get字典onedict
1条回答
网友
1楼 · 发布于 2024-06-24 13:18:33

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

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

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

同样的原则也适用于默认的dict。记住正确实例化默认dict

>>> 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']

相关问题 更多 >