any way to destructure a dict in python like es6 in js?

Viewed 1779

If I have a dict like this:

 dict1 =  {'version': 0, 'name': 'JSESSIONID', 'value': 'AFCF8A9D8AB9E7B701A4D60EE7D8C475.prdaccountc-108', 'port': None, 'port_specified': False, 'domain': 'signin.ea.com', 'domain_specified': False, 'domain_initial_dot': False, 'path': '/p', 'path_specified': True, 'secure': True, 'expires': None, 'discard': True, 'comment': None, 'comment_url': None, 'rfc2109': False, '_rest': {'HttpOnly': None, 'SameSite': 'None'}}

I want to destructure that dict and get it's values like this:

version, name, value = dict1

instead of doing this:

version = dict1["version"]
name = dict1["name"]
value = value["value"]

when I tried to do this I got ValueError: too many values to unpack

3 Answers

You could use dict.values(),make sure the order is what you want(Python >= 3.6):

version, name, value = dict1.values()

If the length of dict1 is larger than the amount of receiver,Try:

version, name, value, *other = dict1.values()
from operator import itemgetter

params = {'a': 1, 'b': 2}

a, b = itemgetter('a', 'b')(params)

as well use a built in library.

You can destruct your dict using **kwargs inside a function:

def destructor(**kwargs):
    # You can access any of your dict keys directly
    # For example:
    print(port, value)

destructor(dict1) # output: AFCF8A9D8AB9E7B701A4D60EE7D8C475.prdaccountc-108 None
Related