100
votes

I am trying to 'destructure' a dictionary and associate values with variables names after its keys. Something like

params = {'a':1,'b':2}
a,b = params.values()

But since dictionaries are not ordered, there is no guarantee that params.values() will return values in the order of (a, b). Is there a nice way to do this?

14
Lazy? Maybe... but of course I've shown the simplest case for illustration. Ideally I wanted to do have like for x in params.items: eval('%s = %f' % x) but I guess eval() doesn't allow assignments. - hatmatrix
@JochenRitzel I'm pretty sure most users of ES6 (JavaScript) likes the new object destructuring syntax: let {a, b} = params. It enhances readability and is completely inline with whatever Zen you want to talk about. - Andy
@Andy I love object destructuring in JS. What a clean, simple and readable way to extract some keys from a dict. I came here with the hope of finding something similar in Python. - Rotareti
I also love ES6 object destructuring, but I'm afraid it can't work in Python for the same reason ES6's Map object doesn't support destructuring. Keys aren't just strings in ES6 Map and Python dict. Also, although I love the "pluck" style of object destructuring in ES6, the assignment style is not simple. What's going on here? let {a: waffles} = params . It takes a few seconds to figure it out even if you're used to it. - John Christopher Jones
@naught101 Situationally useful with nasty surprises for tradeoffs. For users: In Python any object can provide its own str/repr methods. It might even be tempting to do this for slightly complex key objects (e.g., named tuples) for easier JSON serialization. Now you're left scratching your head why you can't destructure a key by name. Also, why does this work for items but not attrs? Lots of libraries prefer attrs. For implementers, this ES6 feature confuses symbols (bindable names) and strings: reasonable in JavaScript but Python has much richer ideas in play. Also, it'd just look ugly. - John Christopher Jones

14 Answers

10
votes

If you are afraid of the issues involved in the use of the locals dictionary and you prefer to follow your original strategy, Ordered Dictionaries from python 2.7 and 3.1 collections.OrderedDicts allows you to recover you dictionary items in the order in which they were first inserted

163
votes
from operator import itemgetter

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

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

Instead of elaborate lambda functions or dictionary comprehension, may as well use a built in library.

32
votes

One way to do this with less repetition than Jochen's suggestion is with a helper function. This gives the flexibility to list your variable names in any order and only destructure a subset of what is in the dict:

pluck = lambda dict, *args: (dict[arg] for arg in args)

things = {'blah': 'bleh', 'foo': 'bar'}
foo, blah = pluck(things, 'foo', 'blah')

Also, instead of joaquin's OrderedDict you could sort the keys and get the values. The only catches are you need to specify your variable names in alphabetical order and destructure everything in the dict:

sorted_vals = lambda dict: (t[1] for t in sorted(dict.items()))

things = {'foo': 'bar', 'blah': 'bleh'}
blah, foo = sorted_vals(things)
21
votes

Python is only able to "destructure" sequences, not dictionaries. So, to write what you want, you will have to map the needed entries to a proper sequence. As of myself, the closest match I could find is the (not very sexy):

a,b = [d[k] for k in ('a','b')]

This works with generators too:

a,b = (d[k] for k in ('a','b'))

Here is a full example:

>>> d = dict(a=1,b=2,c=3)
>>> d
{'a': 1, 'c': 3, 'b': 2}
>>> a, b = [d[k] for k in ('a','b')]
>>> a
1
>>> b
2
>>> a, b = (d[k] for k in ('a','b'))
>>> a
1
>>> b
2
14
votes

Here's another way to do it similarly to how a destructuring assignment works in JS:

params = {'b': 2, 'a': 1}
a, b, rest = (lambda a, b, **rest: (a, b, rest))(**params)

What we did was to unpack the params dictionary into key values (using **) (like in Jochen's answer), then we've taken those values in the lambda signature and assigned them according to the key name - and here's a bonus - we also get a dictionary of whatever is not in the lambda's signature so if you had:

params = {'b': 2, 'a': 1, 'c': 3}
a, b, rest = (lambda a, b, **rest: (a, b, rest))(**params)

After the lambda has been applied, the rest variable will now contain: {'c': 3}

Useful for omitting unneeded keys from a dictionary.

Hope this helps.

11
votes

Maybe you really want to do something like this?

def some_func(a, b):
  print a,b

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

some_func(**params) # equiv to some_func(a=1, b=2)
5
votes

How come nobody posted the simplest approach?

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

a, b = params['a'], params['b']
3
votes

Warning 1: as stated in the docs, this is not guaranteed to work on all Python implementations:

CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None.

Warning 2: this function does make the code shorter, but it probably contradicts the Python philosophy of being as explicit as you can. Moreover, it doesn't address the issues pointed out by John Christopher Jones in the comments, although you could make a similar function that works with attributes instead of keys. This is just a demonstration that you can do that if you really want to!

def destructure(dict_):
    if not isinstance(dict_, dict):
        raise TypeError(f"{dict_} is not a dict")
    # the parent frame will contain the information about
    # the current line
    parent_frame = inspect.currentframe().f_back

    # so we extract that line (by default the code context
    # only contains the current line)
    (line,) = inspect.getframeinfo(parent_frame).code_context

    # "hello, key = destructure(my_dict)"
    # -> ("hello, key ", "=", " destructure(my_dict)")
    lvalues, _equals, _rvalue = line.strip().partition("=")

    # -> ["hello", "key"]
    keys = [s.strip() for s in lvalues.split(",") if s.strip()]

    if missing := [key for key in keys if key not in dict_]:
        raise KeyError(*missing)

    for key in keys:
        yield dict_[key]
In [5]: my_dict = {"hello": "world", "123": "456", "key": "value"}                                                                                                           

In [6]: hello, key = destructure(my_dict)                                                                                                                                    

In [7]: hello                                                                                                                                                                
Out[7]: 'world'

In [8]: key                                                                                                                                                                  
Out[8]: 'value'

This solution allows you to pick some of the keys, not all, like in JavaScript. It's also safe for user-provided dictionaries

2
votes

Look for other answers as this won't cater to the unexpected order in the dictionary. will update this with a correct version sometime soon.

try this

data = {'a':'Apple', 'b':'Banana','c':'Carrot'}
keys = data.keys()
a,b,c = [data[k] for k in keys]

result:

a == 'Apple'
b == 'Banana'
c == 'Carrot'
1
votes

Well, if you want these in a class you can always do this:

class AttributeDict(dict):
    def __init__(self, *args, **kwargs):
        super(AttributeDict, self).__init__(*args, **kwargs)
        self.__dict__.update(self)

d = AttributeDict(a=1, b=2)
0
votes

Based on @ShawnFumo answer I came up with this:

def destruct(dict): return (t[1] for t in sorted(dict.items()))

d = {'b': 'Banana', 'c': 'Carrot', 'a': 'Apple' }
a, b, c = destruct(d)

(Notice the order of items in dict)

0
votes

With Python 3.10, you can do:

d = {"a": 1, "b": 2}

match d:
    case {"a": a, "b": b}:
        print(f"A is {a} and b is {b}")

but it adds two extra levels of indentation, and you still have to repeat the key names.

-1
votes

Since dictionaries are guaranteed to keep their insertion order in Python >= 3.7, that means that it's complete safe and idiomatic to just do this nowadays:

params = {'a': 1, 'b': 2}
a, b = params.values()
print(a)
print(b)

Output:

1
2
-3
votes

I don't know whether it's good style, but

locals().update(params)

will do the trick. You then have a, b and whatever was in your params dict available as corresponding local variables.