convert dictionary entries into variables - python

后端 未结 6 1357
长发绾君心
长发绾君心 2020-11-28 22:58

Is there a pythonic way to assign the values of a dictionary to its keys, in order to convert the dictionary entries into variables? I tried this out:

>&g         


        
6条回答
  •  失恋的感觉
    2020-11-28 23:33

    Consider the "Bunch" solution in Python: load variables in a dict into namespace. Your variables end up as part of a new object, not locals, but you can treat them as variables instead of dict entries.

    class Bunch(object):
        def __init__(self, adict):
            self.__dict__.update(adict)
    
    d = {'a':1, 'b':2}
    vars = Bunch(d)
    print vars.a, vars.b
    

提交回复
热议问题