.get with tuples with dictionaries

T. *_*een 2 python dictionary tuples python-3.x

假设我有一个以元组为例的字典作为键

dictionary = {('a','b'):1, ('c','d'):2}
Run Code Online (Sandbox Code Playgroud)

None如果您在使用时尝试使用不在字典中的键来查找值,是否可以返回.get()

我试过了

dictionary.get('a','c')
Run Code Online (Sandbox Code Playgroud)

但这会返回一个整数,我试过了

dictionary.get(['a','c'])
Run Code Online (Sandbox Code Playgroud)

dictionary.get([('a','c')])
Run Code Online (Sandbox Code Playgroud)

但两者都返回一个类型错误.

Sto*_*ica 7

('a', 'c')用作键,您需要这样写:

dictionary.get(('a', 'c'))
Run Code Online (Sandbox Code Playgroud)

注意加倍括号,这样就必须将元组作为关键参数传递.

如果你写dictionary.get('a', 'c'),这意味着这'a'是获取的关键,并且'c'是在密钥不存在的情况下返回的默认值.

并且dictionary.get(['a','c'])无法工作,因为它[...]是一个列表,而且它不是可清除类型.并且在任何情况下['a', 'c']都不等于('a', 'c'),所以无论如何也不会匹配.