create dictionary from list of variables

前端 未结 6 775
暖寄归人
暖寄归人 2021-02-07 00:26

I\'m looking for a way to create dictionary without writing the key explicitly I want to create function that gets number variables, and create dictionary where the variables na

6条回答
  •  醉酒成梦
    2021-02-07 01:02

    You can't do it without writing at least the variable names, but a shorthand can be written like this:

    >>> foo = 1
    >>> bar = 2
    >>> d = dict(((k, eval(k)) for k in ('foo', 'bar')))
    >>> d
    {'foo': 1, 'bar': 2}
    

    or as a function:

    def createDict(*args):
         return dict(((k, eval(k)) for k in args))
    
    >>> createDict('foo','bar')
    {'foo': 1, 'bar': 2}
    

    you can also use globals() instead of eval():

    >>> dict(((k, globals()[k]) for k in ('foo', 'bar')))
    

提交回复
热议问题