从dicts列表中,返回dicts列表,但仅返回特定的键/值对

时间:2017-09-18 14:34:48

标签: python python-3.x

例如,我原本会有一个像这样的词典列表:

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere rep",
    "body": "quia et suscipit"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vita"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi"
  }
]

如果我有一个例如['id', 'body']的列表,我希望我的新词典列表是:

[
  {
    "id": 1,
    "body": "quia et suscipit"
  },
  {
    "id": 2,
    "body": "est rerum tempore vita"
  },
  {
    "id": 3
  }
]

4 个答案:

答案 0 :(得分:1)

dict_list = [
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere rep",
    "body": "quia et suscipit"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vita"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi"
  }
]

keys = ['id', 'body']

result = [{k: d[k] for k in keys if k in d} for d in dict_list]

print(result)
>>> [{'body': 'quia et suscipit', 'id': 1},
     {'body': 'est rerum tempore vita', 'id': 2},
     {'id': 3}]

执行此操作的行是result = [{k: d[k] for k in keys if k in d} for d in dict_list]。这是一种列表理解,可为dict中的每个dict创建dict_list,仅保留keys列表中的键。

答案 1 :(得分:1)

使用dict理解和过滤键来重建列表中的dicts:

result = [{k:v for k,v in d.items() if k in ["id","body"]} for d in dlist]

print(result)

输出:

[{'body': 'quia et suscipit', 'id': 1}, {'body': 'est rerum tempore vita', 'id': 2}, {'id': 3}]

答案 2 :(得分:0)

list_of_dicts = [
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere rep",
    "body": "quia et suscipit"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vita"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi"
  }
]
item = "body"  # Item to be searched for
for i in list_of_dicts:
    print(i)
    if item in i:
        print("yes")
    else:
        print("no")

您可以使用任何操作替换打印,并添加/更改为“项目”

答案 3 :(得分:0)

使用list comprehension重建dict:

new_dict= [{"id":i["id"], "body":i["body"]} for i in d]