Skip to content
Advertisement

Is there any straightforward option of unpacking a dictionary?

If I do something like this

some_obj = {"a": 1, "b": 2, "c": 3}
first, *rest = some_obj

I’ll get a list, but I want it in 2 dictionaries: first = {"a": 1} and rest = {"b": 2, "c": 3}. As I understand, I can make a function, but I wonder if I can make it in one line, like in javascript with spread operator.

Advertisement

Answer

I don’t know if there is a reliable way to achieve this in one line, But here is one method.

First unpack the keys and values(.items()). Using some_obj only iterate through the keys.

>>> some_obj = {"a":1, "b":2, "c": 3}
>>> first, *rest = some_obj.items()

But this will return a tuple,

>>> first
('a', 1)
>>> rest
[('b', 2), ('c', 3)]

But you can again convert back to dict with just a dict call.

>>> dict([first])
{'a': 1}
>>> dict(rest)
{'b': 2, 'c': 3}
Advertisement