logo
down
shadow

Remove all occurences of a value from a nested dictionary


Remove all occurences of a value from a nested dictionary

By : Lynn P
Date : October 25 2020, 07:10 AM
around this issue You can use a DFS:
code :
def remove_keys(d, keys):
    if isinstance(d, dict):
        return {k: remove_keys(v, keys) for k, v in d.items() if k not in keys}
    else:
        return d
from pprint import pprint
pprint(remove_keys(myDict, ['state']))
{'Stars': {'BookA': {'Mystery': {'AuthorA': {'id': '100'},
                                 'AuthorB': {'id': '112'}},
                     'Thriller': {'Store1': {'id': '300'}},
                     'id': 10}},
 'id': 10}


Share : facebook icon twitter icon
Python dictionary: sum up numerical and remove 'None' values from nested dictionary and assign results to keys of first

Python dictionary: sum up numerical and remove 'None' values from nested dictionary and assign results to keys of first


By : Marquis Tan
Date : March 29 2020, 07:55 AM
may help you . It might be very simple but at the moment, I just don't find a solution for my problem. , Updated to reflect new question data:
code :
clean_pps = {k: sum(filter(None, v.values())) for k, v in list_of_pps.items()}
update nested dictionary values from another nested dictionary based on mapping already provided in the dictionary

update nested dictionary values from another nested dictionary based on mapping already provided in the dictionary


By : Ryan Kruskamp
Date : March 29 2020, 07:55 AM
this one helps. In your function find_input_value you are not propagating the output through the recursions properly. Recursive functions need to have consistent return values. You have 2 returns that send a result and 1 that sends a None. Here is a version that works for me, even though I suspect it can be simplified.
code :
def find_input_value(k,input_json):  
  if k in input_json:
    val = input_json[k]
  for v in input_json.values():
    if 'val' in locals(): #check if val has been defined
      if val is not None: #needs to be defined and not None
        break             # kill the loop cause found it
    if isinstance(v, dict):
      val = find_input_value(k,v)
  return val if 'val' in locals() else None # if input_json is not dict return None
how to remove a key from nested dictionary?

how to remove a key from nested dictionary?


By : user3473351
Date : March 29 2020, 07:55 AM
This might help you I have a nested dictionary:
code :
d = {'a':{'a1':1,'a2':2},
'b':{'b1':1,'b2':2},
'c':{'c1':1,'c2':2}}

del d['a']['a1']
Remove nested key from dictionary

Remove nested key from dictionary


By : Caroline Deng
Date : March 29 2020, 07:55 AM
this will help When working with a subscript, if the subscript is get/set and the variable is mutable, then the entire expression is mutable. However, due to the type cast the expression "loses" the mutability. (It's not an l-value anymore).
The shortest way to solve this is by creating a subscript that is get/set and does the conversion for you.
Remove some field from nested dictionary?

Remove some field from nested dictionary?


By : lks.avi
Date : March 29 2020, 07:55 AM
it helps some times Well, internally you have to process the items one by one, either by manual iteration or recursion.
Here's an attempt using recursion:
code :
def remove_keys(d, to_remove):
    if not isinstance(d, dict):
        return d
    return {k: remove_keys(v, to_remove)
            for k, v in d.items() if k not in to_remove}
remove_keys(d, {"a"})
def remove_keys_m(d, to_remove):
    if not isinstance(d, dict):
        return d
    for k in to_remove:
        if k in d:
            del d[k]
    for k in d:
            d[k] = remove_keys(d[k], to_remove)
    return d
Related Posts Related Posts :
  • Percent signs in windows path
  • How to add a random number to a subsection of a numpy array?
  • How to generate all the values of an iterable besides the last few?
  • Searching by both class and range in XPath
  • Python code execution in Perl interpreter
  • Best Way to Include Variable in Python3
  • Serialize the @property methods in a Python class
  • What is the most platform- and Python-version-independent way to make a fast loop for use in Python?
  • Good way to edit the previous defined class in ipython
  • Bounced email on Google App Engine
  • Search jpeg files using python
  • Dynamically create class attributes
  • python unichr problem
  • Python beginner, strange output problem
  • Python: Finding a value in 1 list and finding that corresponding index in another list
  • can't install mysqlclient on mac os x mojave
  • Error indicates flattened dimensions when loading pre-trained network
  • how to replace underlines with words?
  • Adding through iteration
  • Use OpenCV on deployed Flask app (Heroku)
  • How to skip interstitial in a django view if a user hits the back button?
  • Any Naive Bayesian Classifier in python?
  • Python 2.5.2: remove what found between two lines that contain two concrete strings
  • Python 2.5.2 script that add "The function starts here" to all the functions of the files of a directory
  • HttpResponseRedirect question
  • Python socket error on UDP data receive. (10054)
  • Encoding issues with cloud ml
  • numpy.where - Weird behaviour: new elements spawning from nowhere?
  • I can't move my player in pygame, can you figure why?
  • Weird error I receive from Tkinter in Python
  • Using a Zapier Custom Request Webhook with JSON Web Tokens
  • Keras: Use categorical_crossentropy without one-hot encoded array of targets
  • Does python's httplib.HTTPConnection block?
  • Do alternate python implementation version numbers imply that they provide the same syntax?
  • Searching for specific HTML string using Python
  • python sax error "junk after document element"
  • MySql: How to know if an entry is compressed or not
  • Return a list of imported Python modules used in a script?
  • Returning a list in this recursive coi function in python
  • Python2.6 Decimal to Octal
  • Appengine Apps Vs Google bot web crawler
  • Changing models in django results in broken database?
  • Global variable functions
  • Using lambda inside a function
  • How to open a file, replace some strings, and save updates to the same file?
  • How to move the beginning of an input to the and?
  • If else fill variable if empty list
  • Pandas: Find and print all floats in column
  • sqlite3.OperationalError: database is locked - non-threaded application
  • How to implement mib module in net-snmp with python?
  • Does Python/Scipy have a firls( ) replacement (i.e. a weighted, least squares, FIR filter design)?
  • sorl-thumbnail and file renaming
  • Python -- what is NOT in 2.7 that IS in 3.1? So many things have been back-ported, what is NOT?
  • How to make a Django model fields calculated at runtime?
  • Django - Threading in views without hanging the server
  • Python: Why is my POST requests not working?
  • Tried to add a value to a while condition, but it doesn't go back
  • How do I exit a while-true loop after 5 tries?
  • win python3 Multithreading
  • Compare 2 dictionaries in python
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk