进行过滤,从输入列表中返回所有字典的列表,其中包含指定的键:值对

时间:2019-10-11 09:02:41

标签: python

filterIn 用三个参数定义一个名为filterIn的函数。传递给函数的第一个参数应为字典列表(数据),第二个为字符串(字典键),第三个为其他字符串(字典值)。此函数必须返回输入列表中所有字典的列表,其中包含指定的key:value配对。

我该如何解决这个问题? 这就是我到目前为止所拥有的。

def filterIn (data, key , x):
  result = []
  for i in data:
    if i == (key, x):
  return (result.append(key, x))

2 个答案:

答案 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)

这里有几个问题:

  1. 在进行for i in data时,由于data是词典列表,所以i现在是字典。因此,您的行i == (key, x)没有意义。它应该看起来像: (key, x) in i.items(),或通过get使用i.get(key) == x方法。

  2. 您要返回具有该对的词典列表,因此要在i列表中附加result。因此,您的行result.append(key, x)应该是result.append(i)

  3. append缩进在这里是错误的。如果if子句为True

  4. ,则要追加字典

因此,它看起来应该像:

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]