-1

I have the following dictionary and I was wondering if there was a way to delete objects based off a key value when they are within a list. For instance,

 {'Root': [{'ID': '1', 'version': '3'},{'ID': '2', 'version': '4'},{'ID': '3', 'version': '3'}]}

Is there a way to delete everything in the list that has version == 3 ? This post seems to be almost at the answer, but I have that additional "Root" layer: Remove dictionary from list Thanks for any help!

Shak
  • 103
  • 8
  • 2
    That post *is* the answer. If you don't understand how to apply that answer to an element of a dictionary, then slow down and find a good Python tutorial to pick up the basics. That sort of elementary data structure manipulation is absolutely *necessary* to do anything of substance, not just in Python, but in any programming language. – Silvio Mayolo Jun 07 '21 at 02:50
  • Just grab the list in Root and apply the filtering from the other answer to it. Then either reassign it to the Root key or just create a new outer dict with a root key. – Paul Rooney Jun 07 '21 at 02:53

3 Answers3

1

Try this:

new_dict['root'] = [element for element in old_dict['root'] if element['version'] !='3' ] 
Andres Silva
  • 874
  • 1
  • 7
  • 26
0

What you could do is start iterating over the list from : for element in my_dict['Root']: and then get that element i.e, the dictionary, and then fetch the value of that dictionary 's version.

my_dict={'Root': [{'ID': '1', 'version': '3'},{'ID': '2', 'version': '4'},{'ID': '3', 'version': '3'}]}
new_dict={}
for element in my_dict['Root']:
    if element['version']!="3":
        new_dict.update({"Root":[element]})
print(new_dict)
0

Try this, it will only print the items with version 4:-

a_dict= {"Root": [{"ID": 1, "version": 3},{"ID": 2, "version": 4},{"ID": 3, "version": 3}]}
new_dict = {}

for item in a_dict['Root']:
   if item['version'] != 3:
      print(item)
      new_dict.update({'Root':[item]})

print(new_dict)

It will only print versions which are not 3.