如何通过同时使用多个键来提取字典值 [英] How to extract dictionary values by using multiple keys at the same time

查看:925
本文介绍了如何通过同时使用多个键来提取字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下问题.

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

常规检索方法:dict1['a']->输出-> 1
预期方法:dict1['a', 'b']->输出-> [1, 2]

Normal retrieval method: dict1['a'] -> Output - > 1
expected method: dict1['a', 'b'] - > Output - > [1, 2]

我的要求是,通过上述预期方法中同时提供多个键,从字典中提取多个值.

My requirement is to extract multiple values from a dictionary by providing multiple keys at the same time as mentioned in the expected method above.

有办法吗?如果必须编辑内置的dict类方法,该怎么做?

Is there a way to do it? If I have to edit the built-in dict class methods, how do I do it?

推荐答案

您可以使用列表理解:[dict1[key] for key in ('a', 'b')]

You can use list comprehension : [dict1[key] for key in ('a', 'b')]

它等效于

output = []
for key in ('a', 'b'):
    output.append(dict1[key])

这篇关于如何通过同时使用多个键来提取字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆