Home > OS >  Remove a specific key but not the value( list) , so it becomes an element of upper key
Remove a specific key but not the value( list) , so it becomes an element of upper key

Time:10-02

I don't know if I am able to express myself in the title,

Example dict:

dict_x = {"key1": "value1", "key2": [{"key3": "value3"}, {"key4": [{"key5": "value5"}, {"key6": 
"value6"}]}]}

Edit: think that you have many nested dicts like this. You have to loop through.
Edit2 : We need a recursive approach for hugely nested dicts
what do I want to get as output:

{"key1": "value1", "key2": [{"key3": "value3"}, {"key5": "value5"}, {"key6": "value6"}]}

so removing key4 but retaining the values and pass it to upper key as values.

I searched through stackoverflow but only solutions that are given is to flatten dict or removing keys with values they hold. I want to remove a key but I don't want to lose its values.

CodePudding user response:

Here is a generic solution using a dictionary comprehension:

from itertools import chain
{k1: list(chain(*(list(d.values())[0] if all(map(lambda x: isinstance(x, list), d.values())) else [d]
      for d in v1)))
     if isinstance(v1, list) else v1
 for k1,v1 in dict_x.items()}

And a solution using a classical loop:

out = {}
for k,v in dict_x.items():
    if isinstance(v, list):
        l = []
        for elem in v:
            if all(map(lambda x: isinstance(x, list), elem.values())):
                l.extend([i for sub in elem.values() for i in sub])
            else:
                l.append(elem)
        out[k] = l
    else:
        out[k] = v

output:

{'key1': 'value1',
 'key2': [{'key3': 'value3'}, {'key5': 'value5'}, {'key6': 'value6'}]}

CodePudding user response:

Your dict is quite strange to be honest, but what you want is pop the values then reinsert them.

values = dict_x["key2"].pop(1) #this removes the item and saves it in "values"
dict_x["key2"].extend(values["key4"]) #then extend the existing list with the content
  • Related