2024-06-24 13:18:33 发布
网友
我正在使用python 3.xxx
我在字典里存了一整串字符串
dict = { 'somekey' = '['one','two','three'...]......... *to n*}
现在,如果我知道key = 'somekey',我如何检索值,整个列表。我试过了
key = 'somekey'
dict.get(key,0)
但它不起作用
首先,避免使用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']
首先,避免使用python关键字作为变量名,这会导致shadowing,这会导致很难找到bug
要从字典中获取值,只需使用键对字典进行索引
同样的原则也适用于默认的dict。记住正确实例化默认dict
这将处理列表,包括混合类型的列表:
相关问题 更多 >
编程相关推荐