create dictionary from list of variables

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

提交回复
热议问题