python - 使用多个键之一过滤字典

标签 python dictionary filter

我是 Pyhton 的新手,想用由两个值组成的键来过滤字典。这是我的字典:

{(0, 'DRYER'): [103.0, 131.0, 9.0, 1.24],
 (2, 'DRYER'): [106.0, 120.0, 5.0, 1.24],
 (2, 'WASHING'): [70.0, 90.0, 11.0, 0.19]}

键由两个值 (n,a) 组成我想创建一个新字典,其中 n=2 ,结果是:

{(2, 'DRYER'): [106.0, 120.0, 5.0, 1.24],
 (2, 'WASHING'): [70.0, 90.0, 11.0, 0.19]}

如果有人能帮忙,我将不胜感激!

最佳答案

使用字典理解检查元组键的第一个值是否为 2:

{k: v for k, v in dct.items() if k[0]==2}

所以:

In [11]: dct = {(0, 'DRYER'): [103.0, 131.0, 9.0, 1.24],
    ...:  (2, 'DRYER'): [106.0, 120.0, 5.0, 1.24],
    ...:  (2, 'WASHING'): [70.0, 90.0, 11.0, 0.19]}
    ...:  

In [12]: {k: v for k, v in dct.items() if k[0]==2}
Out[12]: 
{(2, 'DRYER'): [106.0, 120.0, 5.0, 1.24],
 (2, 'WASHING'): [70.0, 90.0, 11.0, 0.19]}

关于python - 使用多个键之一过滤字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49372995/

相关文章:

python - Python 中的嵌套字符串替换为正则表达式

python - 导入错误: No module named readability

python - 添加字典而不是覆盖 - defaultdict

filter - 选择属性mysql

filter - 注册相同类型的 FilterRegistrationBean 两次

java - 如何根据 Java 中的参数值进行分派(dispatch)?

python - jmespath:区分未找到的键和具有空值的键

python - 使用 Python 将列表 l 中以 'S' 开头的项目保存到 l2

c# - 如何使用一系列键搜索 C# 字典?

android - 非法状态异常 : The content of the adapter has changed but ListView did not receive a notification