create dictionary from list of variables

前端 未结 6 776
暖寄归人
暖寄归人 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 00:41

    No, there isn't, because Python functions don't get information about the variables used to call the function. Also, imagine doing something like this:

    create_dict_from_variables(first_name[:-3] + "moo", last_name[::2])
    

    The function will have no way of knowing the expressions used to create the parameters.

    0 讨论(0)
  • 2021-02-07 00:42

    You cannot do this.

    Your function could be defined as:

    def create_dict_from_variables(first_name, second_name):
        return something_from(first_name, second_name)
    

    and you can call this function:

    create_dict_from_variables('abcd', 'efgh')
    

    These two arguments 'abcd' and 'efgh' are not named variables.

    0 讨论(0)
  • 2021-02-07 00:44

    In principle this is possible by passing variable names to function create_dict and then reaching to a caller stack frame from within create_dict function using module inspect.

    0 讨论(0)
  • 2021-02-07 00:45

    In fact, there is a way:

    from varname import nameof
    
    def foo(first_name,second_name):
        return {nameof(first_name):first_name, nameof(second_name):second_name}
    
    first_name = "daniel"
    second_name = "daniel"
    
    print (foo(first_name,second_name))
    

    Output:

    {'first_name': 'daniel', 'second_name': 'daniel'}
    

    You can get the python-varname package below:

    https://github.com/pwwang/python-varname

    Basic use:

    from varname import nameof
    
    s = 'Hey!'
    
    print (nameof(s))
    

    Output:

    s
    
    0 讨论(0)
  • 2021-02-07 01:01

    You can use locals, but I would recommend against it. Do it explicitly.

    >>> import this
    [...]
    Explicit is better than implicit.
    [...]
    

    Your code will generally be better, more predictable, less prone to breaking and more comprehensible if you do it explicitly.

    0 讨论(0)
  • 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')))
    
    0 讨论(0)
提交回复
热议问题