Skip to content Skip to sidebar Skip to footer

How Can I Replace A Key-value Pair In A Nested Dictionary With The Value From The Same Key-value Pair?

I want to replace the key-value pair in a directory with the value from the same key-value pair. In simple words, I want to replace {k1:{key1:value1},k2:{Key2:value2}} with {k1:val

Solution 1:

If all the keys in the inner dictionaries are 0 you can just do:

{k:v[0] for k,v in data.items()}

In case you want to ignore the keys of the inner dictionaries without knowing the value, you can see how this example works:

>>> data={'k1': {'key1': 'value1'}, 'k2': {'key2': 'value2'}}
>>> {k:list(v.values())[0] for k,v indata.items()}
{'k1': 'value1', 'k2': 'value2'}

Post a Comment for "How Can I Replace A Key-value Pair In A Nested Dictionary With The Value From The Same Key-value Pair?"