Destructuring-bind dictionary contents
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
Destructuring dicts and objects in Python
You can use operator
module from standard library as follows:
from operator import attrgetter
id, email, gender, username = attrgetter('id', 'email', 'gender', 'username')(current_user)
print(id, email, gender, username)
In case you have a dict like from your examplecurrentUser = {
"id": 24,
"name": "John Doe",
"website": "http://mywebsite.com",
"description": "I am an actor",
"email": "example@example.com",
"gender": "M",
"phone_number": "+12345678",
"username": "johndoe",
"birth_date": "1991-02-23",
"followers": 46263,
"following": 345,
"like": 204,
"comments": 9
}
just use itemgetter
instead of attrgetter
:from operator import itemgetter
id, email, gender, username = itemgetter('id', 'email', 'gender', 'username')(currentUser)
print(id, email, gender, username)
Divide a dictionary into variables
Problem is that dicts are unordered, so you can't use simple unpacking of d.values()
. You could of course first sort the dict by key, then unpack the values:
# Note: in python 3, items() functions as iteritems() did
# in older versions of Python; use it instead
ds = sorted(d.iteritems())
name0, name1, name2..., namen = [v[1] for v in ds]
You could also, at least within an object, do something like:for k, v in dict.iteritems():
setattr(self, k, v)
Additionally, as I mentioned in the comment above, if you can get all your logic that needs your unpacked dictionary as variables in to a function, you could do:def func(**kwargs):
# Do stuff with labeled args
func(**d)
ES6-like Python dict spread
No this isn't really possible. You can't have
a, b, c = spread(d)
and a, c, b = spread(d)
give the same value to b
. This is because the right side of an assignment statement is evaluated first. So spread
executes and returns its values before your code knows which order you put them in on the left. Some googling leads be to believe that by "spread-like syntax for dicts", you're looking for the **dict
syntax. See What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
Return copy of dictionary excluding specified keys
You were close, try the snippet below:
>>> my_dict = {
... "keyA": 1,
... "keyB": 2,
... "keyC": 3
... }
>>> invalid = {"keyA", "keyB"}
>>> def without_keys(d, keys):
... return {x: d[x] for x in d if x not in keys}
>>> without_keys(my_dict, invalid)
{'keyC': 3}
Basically, the if k not in keys
will go at the end of the dict comprehension in the above case.
Related Topics
Django: How to Manage Development and Production Settings
Listing Contents of a Bucket with Boto3
How to Create Module-Wide Variables in Python
Wrapping Long Y Labels in Matplotlib Tight Layout Using Setp
How to Format a Date in Jinja2
What Is More 'Pythonic' for 'Not'
Merging Dictionary Value Lists in Python
What's the Difference Between Subprocess Popen and Call (How to Use Them)
Error Importing Scikit-Learn Modules
Why "Numpy.Any" Has No Short-Circuit Mechanism
How to Check If Two Strings Are Anagrams of Each Other
Binary Numpy Array to List of Integers
Python Decompression Relative Performance
Vectorized Numpy Linspace for Multiple Start and Stop Values