Python:使用解包元组作为(dict)键的通用方法

标签 python python-3.x dictionary iterable-unpacking

在 python 中,我们可以解压函数参数,以便获得各个元素:

def printAll(*args):
    print(args, *args)  # packed and unpacked version respectively
printAll(1)  # (1,) 1
printAll(1, 2)  # (1, 2) 1 2

但是,我想定义一个函数(除其他外)使用一些参数访问某个容器(例如字典)。 字典是预定义的,无法修改! 我遇到了以下麻烦:

# e.g. d is a dict with
#    d[1] = 1 <- key is scalar
#    d[1, 2] = 3 <- key is tuple
def accessDict(name, *args):
    print('Hello', name)
    d[args]
    # d[*args] what I'd need, but it's invalid syntax
accessDict('foo', 1)  # should give 1 but gives KeyError because args is (1,) not 1
accessDict('foo', 1, 2)  # should give 3

一种替代方法是添加:

if len(args) == 1:
    return d[args[0]]

但我觉得应该有一种更优雅的方式来做到这一点......

最佳答案

正确的方法是使用一致的 key ,例如:

d = {(1,): 1, (1, 2): 3}

如果你不能,但你需要处理该字典的许多操作,那么预处理它可能是有意义的:

d = {1: 1, (1, 2): 3}
dd = { (k if isinstance(k, tuple) else (k,)): v for k, v in d.items() }

如果您只需要使用几次,那么您可以坚持最初的建议:

def accessDict(name, *args):
    print('Hello', name)
    d[args if len(args) > 1 else d[args[0]]]

关于Python:使用解包元组作为(dict)键的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51535473/

相关文章:

python - 如何让 Powerpoint 自动调整文本

python - Pandas 。 pd.read_csv KeyError :not in index error

python - 字典中的值的字典 KeyError

python - 如何切换 bool argparse 选项?

python - 使用 Anaconda Python 3.5 在 Ubuntu 14.04 上安装 GDAL 时出现导入错误

javascript - 在异步函数内映射数组会导致错误

arrays - 字典中值的总和 - Swift

python - 检查是否填充了多行,如果没有填充所有值

python - 如何用scrapy解析多个页面

python - 以 $$ 作为分隔符在 pandas 中导入 CSV