convert dictionary entries into variables - python

后端 未结 6 1355
长发绾君心
长发绾君心 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:24

    You already have a perfectly good dictionary. Just use that. If you know what the keys are going to be, and you're absolutely sure this is a reasonable idea, you can do something like

    a, b = d['a'], d['b']
    

    but most of the time, you should just use the dictionary. (If using the dictionary is awkward, you are probably not organizing your data well; ask for help reorganizing it.)

    0 讨论(0)
  • This was what I was looking for:

    >>> d = {'a':1, 'b':2}
    >>> for key,val in d.items():
            exec(key + '=val')
    
    0 讨论(0)
  • 2020-11-28 23:31

    Use pandas:

    import pandas as pd
    var=pd.Series({'a':1, 'b':2})
    #update both keys and variables
    var.a=3
    print(var.a,var['a'])
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-28 23:33

    you can use operator.itemgetter

    >>> from operator import itemgetter
    >>> d = {'a':1, 'b':2}
    >>> a, b = itemgetter('a', 'b')(d)
    >>> a
    1
    >>> b
    2
    
    0 讨论(0)
  • 2020-11-28 23:38

    You can do it in a single line with:

    >>> d = {'a': 1, 'b': 2}
    >>> locals().update(d)
    >>> a
    1
    

    However, you should be careful with how Python may optimize locals/globals access when using this trick.

    Note

    I think editing locals() like that is generally a bad idea. If you think globals() is a better alternative, think it twice! :-D

    Instead, I would rather always use a namespace.

    With Python 3 you can:

    >>> from types import SimpleNamespace    
    >>> d = {'a': 1, 'b': 2}
    >>> n = SimpleNamespace(**d)
    >>> n.a
    1
    

    If you are stuck with Python 2 or if you need to use some features missing in types.SimpleNamespace, you can also:

    >>> from argparse import Namespace    
    >>> d = {'a': 1, 'b': 2}
    >>> n = Namespace(**d)
    >>> n.a
    1
    

    If you are not expecting to modify your data, you may as well consider using collections.namedtuple, also available in Python 3.

    0 讨论(0)
提交回复
热议问题