我想知道是否有将字符串转换为字典位置的预构建方式。我认为示例代码将是最简单的解释我想要做的事情。将字符串转换为Python中的字典位置
def main(locate_user_id):
response = {
"users": [{
"id": 1,
"name": "Joe"
}, {
"id": 2,
"name": "Bob"
}]
}
print(response)
print (locate_user_id)
print (response[locate_user_id])
if __name__ == "__main__":
main("users[1]['id']")
的这个输出是目前:
{'users': [{'id': 1, 'name': 'Joe'}, {'id': 2, 'name': 'Bob'}]}
users[1]['id']
Traceback (most recent call last):
File "test_dict.py", line 17, in <module>
main("users[1]['id']")
File "test_dict.py", line 14, in main
print (response[locate_user_id])
KeyError: "users[1]['id']"
而且我正在寻找一个解决方案,将输出这个:
{'users': [{'id': 1, 'name': 'Joe'}, {'id': 2, 'name': 'Bob'}]}
users[1]['id']
2 // the id of the user referenced above
你应该考虑重新设计你的代码。这是糟糕的设计。 –
这里有一些非常残暴的答案。不要使用'eval',而是重新设计代码,以便通过传递int来访问数据。 – skrx