This site uses cookies to deliver our services and to show you relevant ads and job listings.
By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.
Your use of Stack Overflow’s Products and Services, including the Stack Overflow Network, is subject to these policies and terms.

Join us in building a kind, collaborative learning community via our updated
Code of Conduct.

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.
– hatmatrixJun 2 '10 at 10:07

@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.
– RotaretiFeb 17 '17 at 4:04

@Rotareti certainly beats Python's tuple destructuring, where one can easily get the order wrong!
– AndyFeb 17 '17 at 17:04

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 JonesMar 10 at 0:46

7 Answers
7

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

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:

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:

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):