filterIn 用三个参数定义一个名为filterIn的函数。传递给函数的第一个参数应为字典列表(数据),第二个为字符串(字典键),第三个为其他字符串(字典值)。此函数必须返回输入列表中所有字典的列表,其中包含指定的key:value配对。
我该如何解决这个问题? 这就是我到目前为止所拥有的。
def filterIn (data, key , x):
result = []
for i in data:
if i == (key, x):
return (result.append(key, x))
答案 0 :(得分:1)
尝试这样的事情:
def filterIn (data, key , x):
result = []
for dictionary in data:
if dictionary.get(key) == x:
result.append(dictionary)
return result
data = [{1:2, 2:2}, {2:2}, {3:1}]
result = filterIn(data, 2, 2)
print(result)
out: [{1: 2, 2: 2}, {2: 2}]
“对于数据中的i”将在变量“ i”中返回字典,而不是键值对,因此您必须检查键值对是否存在于字典中。您可以通过调用“ get”方法来做到这一点,如果字典中不存在该键,则该方法将返回None。然后,您必须将整个字典添加到结果中,而不仅仅是键值对。
希望这会有所帮助
答案 1 :(得分:0)
这里有几个问题:
在进行for i in data
时,由于data
是词典列表,所以i
现在是字典。因此,您的行i == (key, x)
没有意义。它应该看起来像:
(key, x) in i.items()
,或通过get
使用i.get(key) == x
方法。
您要返回具有该对的词典列表,因此要在i
列表中附加result
。因此,您的行result.append(key, x)
应该是result.append(i)
append
缩进在这里是错误的。如果if
子句为True
因此,它看起来应该像:
def filterIn(data, key, x):
result = []
for i in data:
if i.get(key) == x:
result.append(i)
return i
它可以缩写为:
def filterIn(data, key, x):
return [i for i in data if i.get(key) == x]