【问题标题】:How to extract from a dictionary based on a key value in python如何根据python中的键值从字典中提取
【发布时间】:2022-01-11 17:03:19
【问题描述】:

假设我有一本这样的字典:

{
    "test1": [{
            "key1": "123",
            "key2": "456",
            "key3": null,
            "key4": "Book1"
        }, {
            "key1": "123",
            "key2": "456",
            "key3": null,
            "key4": "Book2"
        }, {
            "key1": "12311",
            "key2": "45678",
            "key3": null,
            "key4": "Book1"
        }, {
            "key1": "123",
            "key2": "456",
            "key3": null,
            "key4": "Book4"

        }, {
            "key1": "12322",
            "key2": "45690",
            "key3": null,
            "key4": "Book1"
        }
    ]
}

我想要的是另一个字典,其中我只有某些键等于某物的元素(在我的情况下,我想保留 key4 = Book1 的所有元素) 我怎样才能有另一个看起来像这样的字典:

{
    "test1": [{
            "key1": "123",
            "key2": "456",
            "key3": null,
            "key4": "Book1"
        }, {
            "key1": "12311",
            "key2": "45678",
            "key3": null,
            "key4": "Book1"
        }, {
            "key1": "12322",
            "key2": "45690",
            "key3": null,
            "key4": "Book1"
        }
    ]
}

【问题讨论】:

  • 您需要编写代码,而您显然还没有尝试过。
  • 嗨@ScottHunter,很抱歉,问题是我什至不知道从哪里开始,并不是我没有寻找解决方案,而是我发现的一切都没有解决我的问题跨度>

标签: python json python-3.x dictionary


【解决方案1】:

首先,python 中没有 null 之类的东西,它是 None。 其次,这可能会以您想要的方式工作

newDict = {"test1": []}
for i in oldDict["test1"]:
    if i['key4'] == 'Book1':
        newdict["test1"].append(i)

【讨论】:

  • 非常感谢@shivang
【解决方案2】:

简单的一个班轮:

{"test1": [d for d in data["test1"] if d["key4"] == "Book1"]}

假设你调用你的初始字典data

【讨论】:

  • 非常感谢@tinu,这个也可以
猜你喜欢
  • 2017-04-09
  • 2014-11-17
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多