简体   繁体   English

从嵌套字典列表中的字典中删除键值对

[英]Delete key:value pair from dict in list in nested dict

Lets say I have this dict:可以说我有这个字典:

dictos = {
    "a": {
        "b": {
            "c": 3,
            "d": 4,
            "e": [],
            "f": [{"g": 5}, 'test', {"h": 6, "i": 7}]
        }
    }
}

And lets say I want to delete "c": 3 pair.假设我想删除 "c": 3 对。 What I am doing:我在做什么:

import dpath.util
path = "a/b/c"
dpath.util.delete(dictos, path)

It is working great.它工作得很好。 The output is: output 是:

{
  'a': {
    'b': {
      'd': 4,
      'e': [],
      'f': [{'g': 5}, 'test', {'h': 6, 'i': 7}]
    }
  }
}

The problem is when I am trying to delete key:value pair inside the list.问题是当我试图删除列表中的键:值对时。 Lets say I want to delete "h":6.比方说我想删除“h”:6。 So when doing:所以在做的时候:

path = "a/b/f[2]/h"
dpath.util.delete(dictos, path)

I am getting:我正进入(状态:

dpath.exceptions.PathNotFound: Could not find a/b/f[2]/h to delete it. dpath.exceptions.PathNotFound:找不到要删除的 a/b/f[2]/h。

So the question basically is how to delete items from nested dicts that are in a list?所以问题基本上是如何从列表中的嵌套字典中删除项目?

It seems the library expects the same separator to be used for all segments ie use a/b/f/2/h似乎图书馆希望所有段都使用相同的分隔符,即使用a/b/f/2/h

path = "a/b/f/2/h"
dpath.util.delete(dictos, path)
print(dictos)

Result:结果:

{'a': {'b': {'d': 4, 'e': [], 'f': [{'g': 5}, 'test', {'i': 7}]}}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 用嵌套的dict键值对创建包含项的列表 - Create a list with items from a nested dict key value pair 提取键值对并转置嵌套字典 - Extracting key value pair and transpose nested dict 如何从具有嵌套字典列表的字典中提取特定键值对 - how to extract a specific key value pair from a dict with a nested list of dicts 如何基于Python中的匹配键将键值对添加到另一个字典列表中的现有字典列表中 - How to append key value pair to an existing list of dict from another list of dict based on matching Key in Python 从列表中划分字母数字词并将其存储为字典的键值对 - Divide alphanumeric word from a list and store as a key value pair of a dict 将 YAML dict 转换为键/值对列表 - Converting YAML dict into key/value pair list 从一个字典中检索一个键值对作为另一个字典 - Retrieve a key-value pair from a dict as another dict 带有嵌套字典的列表中的数据帧,其中第一个字典的键是列和键,第二个字典的值是行和值 - DataFrame from list with nested dicts where key of first dict is column and key, value of second dict is row and value 将dict从键/值对扩展到Python中的键/值对 - Extend dict from key/values pair to key/value pair in Python 如果dict键的值在otherlist中,则从列表中的dicts中删除元素 - Delete elements from dicts in list if value of dict key is in otherlist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM