根据值从嵌套字典中删除键

时间:2016-12-21 16:51:38

标签: python

我早先询问有关添加,有人帮助我追加。我的新问题是尝试删除带有嵌套列表的密钥,例如:

JSON:

data = {"result":[{"name":"Teddy","list":{"0":"24","1":"43","2":"56"}},
           {"name":"Barney","list":{"0":"24","1":"43","2":"56"}]}

Python:

name = input("Input a key to delete") #Must hold a value. 
data["result"].pop(name)

E.g。 Barney =>然后删除Barney等。

我使用下面的方法找到一个键,但我不确定这是正确的方法。 寻找Barney:

for key in data['result']:
   if key['name'] == name:
       print("Found!!!!")

我不确定。这肯定不起作用,也许我应该遍历每个键或?任何建议或代码示例都是值得的。

删除后:现在barney被删除了,字典仍然是这样的。

data = {"result":[{"name":"Teddy","list":{"0":"24","1":"43","2":"56"}}]}

3 个答案:

答案 0 :(得分:0)

您可以将JSON转换为JavaScript对象。

var resultString = '{'result':[{'key1':'value1','key2':'value2'}, {'key1':'value3','key2':'value4'}]}';
var result = JSON.parse(resultString);

一旦你这样做,你应该更加意识到这是一个对象数组。您需要知道要删除的索引。您可以将.find方法用于数组

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

如果您不知道索引。

var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

function findCherries(fruit) { 
    return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); 
// { name: 'cherries', quantity: 5 }

虽然该发现在IE中不起作用。一旦知道索引,就可以拆分数组。

var myFish = ["angel", "clown", "drum", "mandarin", "surgeon"];
var removed = myFish.splice(3, 1);

// removed is ["mandarin"]
// myFish is ["angel", "clown", "drum", "surgeon"]

来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

答案 1 :(得分:0)

由于data['result']list,您必须转到索引并删除密钥。如果您希望删除list中所有索引的键,您可以快速编写一个迭代整个列表并删除匹配键的函数

def delete_key(list_obj, key):
    for value in list_obj:
        if key in value:
            value.pop(key)
    return list_obj

result = delete_key(data["result"], 'key1')

答案 2 :(得分:0)

如果目标是从JSON文档中删除列表项,您需要:

  • 将JSON文档转换为Python数据结构
  • 操纵Python数据结构
  • 将Python数据结构转换回JSON文档

这是一个这样的程序:

import json

def delete_keys(json_string, name):
    data = json.loads(json_string)
    data['result'][:] = [d for d in data['result'] if d.get('name') != name]
    json_string = json.dumps(data)
    return json_string

j = '''
    {"result":[{"name":"Teddy",
                "list":{"0":"24","1":"43","2":"56"}},
               {"name":"Barney","list":{"0":"24","1":"43","2":"56"}}]}'''
print delete_keys(j, 'Barney')

结果:

$ python x.py 
{"result": [{"list": {"1": "43", "0": "24", "2": "56"}, "name": "Teddy"}]}

请注意此列表理解:

data['result'][:] = [d for d in data['result'] if d.get('name') != name]

表单l[:] = [item in l if ...]是根据指示条件从列表中删除多个项目的一种方法。