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

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

问题描述

我遇到了以下问题.

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?

推荐答案

使用列表理解:

[ dict[k] for k in ('a','b')]
[ dict[k] for k in my_iterable ]

如果可迭代项中的任何键不在dict中,则

将抛出KeyError.这样做可能更好

will throw KeyError if any of the keys in the iterable are not in the dict. It may be better to do

[ dict.get(k, my_default_value) for k in my_iterable ]

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

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