Destructuring-bind dictionary contents

2020-01-30 12:08发布

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?

10条回答
叛逆
2楼-- · 2020-01-30 12:18

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
查看更多
神经病院院长
3楼-- · 2020-01-30 12:27

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)
查看更多
ら.Afraid
4楼-- · 2020-01-30 12:29

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)

查看更多
倾城 Initia
5楼-- · 2020-01-30 12:31

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

查看更多
神经病院院长
6楼-- · 2020-01-30 12:36

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)
查看更多
beautiful°
7楼-- · 2020-01-30 12:37

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.

查看更多
登录 后发表回答