carcinogenic
carcinogenic

Reputation: 169

How to convert variable name into string in Python

I want to take the name of a dictionary and turn that into a string. In this case I'm using the variable "Name" to identify the structure, but how can I simply convert the name of this dictionary into a string and eliminate the need for the Name variable altogether?

PbO_57 = {  
            1 : [ 'Pb', (0.231, 0.009, 0.250)  ],   2 : [ 'Pb', (-0.231, -0.009, 0.750) ], 
            3 : [ 'Pb', (-0.231, 0.509, 0.750) ],   4 : [ 'Pb', (0.231, 0.491, 0.250)   ], 
            5 : [ 'O', (0.139, 0.412, 0.250)   ],   6 : [ 'O', (-0.139, -0.412, 0.750)  ],
            7 : [ 'O', (-0.139, 0.912, 0.750)  ],   8 : [ 'O', (0.139, 0.088, 0.250)    ] 
        }    

Name = 'PbO_57'

Here is how I'm currently using the string name in the output:

print('{}\n{} X {} X {} {} supercell\n{}'.format(Line,X,Y,Z,Name,Line))

Which displays the following line:

1 X 1 X 8 PbO_57 supercell

Upvotes: 1

Views: 290

Answers (1)

Panwen Wang
Panwen Wang

Reputation: 3825

I have developed a package (https://github.com/pwwang/python-varname) with a value wrapper that could be used to implement this pretty easily:

from varname import Wrapper

PbO_57 = Wrapper({  
            1 : [ 'Pb', (0.231, 0.009, 0.250)  ],  2 : [ 'Pb', (-0.231, -0.009, 0.750) ], 
            3 : [ 'Pb', (-0.231, 0.509, 0.750) ],  4 : [ 'Pb', (0.231, 0.491, 0.250)   ], 
            5 : [ 'O', (0.139, 0.412, 0.250)   ],  6 : [ 'O', (-0.139, -0.412, 0.750)  ],
            7 : [ 'O', (-0.139, 0.912, 0.750)  ],  8 : [ 'O', (0.139, 0.088, 0.250)    ] 
        })    
# You don't need the hard-coded Name anymore
# Name = 'PbO_57'
#
# Now you can access the dict by PbO_57.value, 
# and the name "PbO_57" by PbO_57.name

print('{}\n{} X {} X {} {} supercell\n{}'.format(Line,X,Y,Z,PbO_57.name,Line))
# 1 X 1 X 8 PbO_57 supercell

Upvotes: 1

Related Questions