python-3.x - 如何从字典中过滤一个值,这个字典在python中包含多个值?
问题描述
我正在尝试这样做,我在其中键入 10 的值,它将过滤掉大于 10 的值并给出结果:
'b':['sam',20], 'c':['rose',30], 'd':['mary',40], 'e':['jon',50]
下面是我正在尝试的代码:
h = int(input("Enter Value: "))
ini_dict = {'a':['abc',10], 'b':['sam',20], 'c':['rose',30], 'd':['mary',40], 'e':['jon',50]}
# printing initial dictionary
print ("initial lists", str(ini_dict))`
result = dict(filter(lambda x: x[1]>h, ini_dict.items()))
result = dict(result)
print("resultant dictionary : ", str(result))
我遇到了这个错误 "TypeError: '>' not supported between instances of 'list' and 'int'" 。除此之外,我还尝试修改:
结果 = dict(filter(lambda x: x[1]>h, ini_dict.items())) 成
这个结果 = dict(filter(lambda x,y:x,y[1]>h, ini_dict.items())) 并遇到错误 y undefined。
谢谢您的帮助!
解决方案
这就是这里的问题:当您键入时,x[1]
您选择的是字典中每个元素中的整个列表。为了访问您需要在列表中的索引,您应该尝试x[1][1]
. 所以像我说的那样修改代码:
h = int(input("Enter Value: "))
ini_dict = {'a':['abc',10], 'b':['sam',20], 'c':['rose',30], 'd':['mary',40], 'e':['jon',50]}
# printing initial dictionary
print ("initial lists", str(ini_dict))
result = dict(filter(lambda x: x[1][1]>h, ini_dict.items()))
result = dict(result)
print("resultant dictionary : ", str(result))
输出:
Enter Value: 10
initial lists {'a': ['abc', 10], 'b': ['sam', 20], 'c': ['rose', 30], 'd': ['mary', 40], 'e': ['jon', 50]}
resultant dictionary : {'b': ['sam', 20], 'c': ['rose', 30], 'd': ['mary', 40], 'e': ['jon', 50]}
推荐阅读
- amazon-web-services - 在“Amazon Linux AMI”上安装 make 4.2
- gpu - Slurm 超额认购 GPU
- c - 标准 C 库中缓冲区大小的特殊宏是什么?
- ios - 子类化 UISlider 以使用 IBDesignable/IBInspectable 自定义拇指图像?
- javascript - 使用 .map() 在 jquery 中分组
- maven - requireProperty 是否不需要 Maven 强制执行器中的典型 Maven 属性?
- firebase - 带有自定义令牌的 Firebase 存储通配符规则
- mysql - OR 运算符减慢 MySQL 查询速度
- r - 如何对变量设置条件
- android - RecyclerView 在最大高度为 WRAP_CONSTRAINT 时无法正确包装其内容