Assigning Variable with Value of Existing Variable from String Value

时间:2016-04-04 20:57:54

标签: python string variables variable-assignment

I have a large amount of data in variable form:

abc_123 = 5  
def_456 = 7  
ghi_789 = 9 

etc.

I ask the user for various inputs, which builds up a string. For example:

temp = "abc_123"

How do I make it so that temp = abc_123, thus making temp = 5?

1 个答案:

答案 0 :(得分:1)

制作词典,然后按键查找值:

>>> d = {"abc_123": 5, "def_456": 7, "ghi_789": 9}
>>> temp = "abc_123"
>>> d[temp]
5
>>> d.get("invalid", "not found")
'not found'