键为元组时访问字典值 [英] Access dictionary value when the key is a tuple

查看:68
本文介绍了键为元组时访问字典值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,我有一个问题,我需要从键为元组的字典中获取值.例如:

I'm new to Python and I have a problem where I need to get the value from a dictionary where the keys are tuples. For example:

ones = {(1,2,6,10):3, (4,5,9):4, (3,7,8):5}

我知道每个数字在键中都出现一个,并且我想访问键中包含数字2的值(该值将为3).

I know that each number appears ones in the keys, and I want to access the value where the key has the number 2 in (the value will be 3).

我可以获取有关如何访问此值的任何帮助吗?

Can I get any help on how to access this value?

推荐答案

您可以使用以下理解来拼合"字典:

You could "flatten" the dictionary using the following comprehension:

ones = {(1,2,6,10):3, (4,5,9):4, (3,7,8):5}

flat = {element: value for key, value in ones.items() for element in key}

现在,您可以通过 flat 从元组中获取任何键的值.

Now you can get the value of any key from the tuples via flat.

这篇关于键为元组时访问字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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