Home > Software engineering >  Keep only the first element of a nested dict
Keep only the first element of a nested dict

Time:06-05

For example, is there a way to change

{'z': {'pl': 0.1001692265,
  'sa': 0.0899505839},
 'y': {'ap': 0.0734830126}}

Into

{'z': {'pl': 0.1001692265},
 'y': {'ap': 0.0734830126}}

I'm looking for a solution that would be dynamic and not just based on the value of the key in this case (i.e. 'sa')

Thanks!

CodePudding user response:

To get the first key-value pair, with d as the original dictionary you can use:

# Using suggestion by Ch3steR
{k:dict([next(iter(v.items()))]) for k, v in d.items()}

Or using itertools.islice as suggesed by MechanicPig

{k:dict(itertools.islice(v.items(), 1)) for k, v in d.items()}

CodePudding user response:

Python3.8

In dict comprehension, we loop over outer dict. We can convert the inner dict to iterator and use next to get the first element. We can use the walrus operator to store the key.

{k: {(k1:=next(iter(v))): v[k1]} for k, v in d.items()}
# {'z': {'pl': 0.1001692265}, 'y': {'ap': 0.0734830126}}

CodePudding user response:

Using itertools.islice is probably the most elegant way:

>>> dct = {'z': {'pl': 0.1001692265, 'sa': 0.0899505839}, 'y': {'ap': 0.0734830126}}
>>> {k: dict(islice(v.items(), 1)) for k, v in dct.items()}
{'z': {'pl': 0.1001692265}, 'y': {'ap': 0.0734830126}}

CodePudding user response:

There's no such thing as the 'first element' of a dictionary. Python dictionaries are unordered.

If you need a dictionary like structure that maintains order, the OrderedDict type of Python's collections library is an option.

  • Related