首页 > 解决方案 > 如何从字典中过滤一个值,这个字典在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。

谢谢您的帮助!

标签: python-3.xdictionary

解决方案


这就是这里的问题:当您键入时,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]}

推荐阅读