VIS*_*ALA 4 python dictionary key list
我遇到了以下问题。
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Run Code Online (Sandbox Code Playgroud)
正常检索方法:dict1['a'] ->输出->1
预期方法:dict1['a', 'b']->输出->[1, 2]
我的要求是通过同时提供多个键从字典中提取多个值,如上面预期方法中所述。
有办法做到吗?如果我必须编辑内置的 dict 类方法,我该怎么做?
您可以按照其他答案中的说明进行操作,或者使用字典方法map在键列表上使用get:
list(map(dict1.get, ["a", "b"]))
Run Code Online (Sandbox Code Playgroud)