Removing a key from a nested dictionary based on value

2024/10/6 11:31:12

I previusly asked about adding, and someone helped me out with append. My new problem is trying to delete a key with a nested list, e.g.:

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 => then delete Barney etc.

I use the method below to find a key, but I am not sure this is the correct approach. Finding Barney:

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

I am not sure. This surely does not work, maybe I should loop through each key or? Any suggestion or code example is worth.

After Delete: Now that barney was deleted the dictionary remains like this.

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

If the goal is to remove list items from the JSON document, you'll want to:

  • Convert the JSON document into a Python data structure
  • Manipulate the Python data structure
  • Convert the Python data structure back to a JSON document

Here is one such program:

import jsondef 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_stringj = '''{"result":[{"name":"Teddy","list":{"0":"24","1":"43","2":"56"}},{"name":"Barney","list":{"0":"24","1":"43","2":"56"}}]}'''
print delete_keys(j, 'Barney')

Result:

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

Note this list comprehension:

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

The form l[:] = [item in l if ...] is one way to delete several items from a list according to the indicated condition.

https://en.xdnf.cn/q/119434.html

Related Q&A

Is dot product and normal multiplication results of 2 numpy arrays same?

I am working with kernel PCA in Python and I have to find the values after projecting the original data to the principal components.I use the equation fv = eigvecs[:,:ncomp]print(len(fv))td = fv.T …

Tkinter Entry widget stays empty in larger programs (Python 2)

I want to make a program where, after clicking on a button, a user gets asked for its name, after which the program continues. Im stuck on making the popup return the textstring that has been entered i…

How do i implement this python tree linked list code in dart?

Here is the python codedef tree(root_label, branches=[]):for branch in branches:assert is_tree(branch), branches must be treesreturn [root_label] + list(branches)def label(tree):return tree[0]def branc…

How can i find the ips in network in python

How can i find the TCP ips in network with the range(i.e 132.32.0.3 to 132.32.0.44) through python programming and also want to know the which ips are alive and which are dead. please send me.. thanks …

Python Coding (call function / return values)

I am having trouble writing code for this question. I have seen this question asked in a few places but I still cannot figure out the answer from the tips they provided. The question is: Write a progr…

discord.py Mention user by name

I am trying to mention a user by their name in discord.py. My current code is: @bot.command(name=mention) @commands.has_role(OwnerCommands) async def mention(ctx, *, member: discord.Member):memberid = …

Python unexpected EOF while parsing : syntax error

I am trying to do a simple toto history with a dictionary and function however I have this funny syntax error that keeps appearing that states "unexpected EOF while parsing" on the python she…

How can I read part of file and write the rest to another file?

I have multiple large csv file. How can I read part of each file and write 10% of the data/rows to another file?

Encryption/Decryption - Python GCSE [duplicate]

This question already has an answer here:Encryption and Decryption within the alphabet - Python GCSE(1 answer)Closed 8 years ago.I am currently trying to write a program, for school, in order to encryp…

Convert decimal to binary (Python) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…