在Python中将字符串转换为字典位置
我试图找出是否有一种预先构建的方法可以将字符串转换为字典位置。我认为示例代码将是最容易解释我要做什么的在Python中将字符串转换为字典位置,python,string,dictionary,Python,String,Dictionary,我试图找出是否有一种预先构建的方法可以将字符串转换为字典位置。我认为示例代码将是最容易解释我要做什么的 def main(locate_user_id): response = { "users": [{ "id": 1, "name": "Joe" }, { "id": 2, "name": "Bob" }] } print(r
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']"
字符串就是字符串。您需要Python解释器才能理解Python语法。要在脚本范围内调用解释器,可以使用
eval
您需要对eval
脚本稍作修改,才能按您想要的方式工作:
def main(locate_user_id):
response = {
"users": [{
"id": 1,
"name": "Joe"
}, {
"id": 2,
"name": "Bob"
}]
}
print(eval('response' + locate_user_id))
if __name__ == "__main__":
main("['users'][1]['id']")
这是在函数main
的范围内评估字符串response['users'][1]['id']
无论使用何种用例,使用
eval
都是不推荐的,因为有很多原因你可以在谷歌上搜索。我将尝试重构您的代码,以便不必使用eval
使用ast.literal\u eval
:
>>> import ast
>>> ast.literal_eval{PUT YOUR LIST HERE}
def main(locate_user_id):
response = {
"users": [{
"id": 1,
"name": "Joe"
}, {
"id": 2,
"name": "Bob"
}]
}
print(("{"+locate_user_id+"}").format(response))
if __name__ == "__main__":
main("[users][1][id]") # instead of "users[1]['id']"
我想这就行了。有点脏,但它能用
def main(locate_user_id):
response = {
"users": [{
"id": 1,
"name": "Joe"
}, {
"id": 2,
"name": "Bob"
}]
}
print(response)
print(locate_user_id)
keys = locate_user_id.replace(']','').split('[')
keys[0] = '"' + keys[0] + '"'
eval_str = '[' + ']['.join(keys) + ']'
print(eval(str(response) + eval_str))
if __name__ == "__main__":
main("users[1]['id']")
无需使用
eval
,只需稍微修改您的输入,您就可以使用str.format
实现您想要的功能,它能够评估下标访问,而无需使用邪恶的eval
:
>>> import ast
>>> ast.literal_eval{PUT YOUR LIST HERE}
def main(locate_user_id):
response = {
"users": [{
"id": 1,
"name": "Joe"
}, {
"id": 2,
"name": "Bob"
}]
}
print(("{"+locate_user_id+"}").format(response))
if __name__ == "__main__":
main("[users][1][id]") # instead of "users[1]['id']"
结果:
2
这里有一种重构代码的方法。该函数现在只获取响应和索引,并打印用户列表的相应元素
response = {
"users": [
{"id": 1, "name": "Joe"},
{"id": 2, "name": "Bob"}
]
}
def locate_user_id(response, user_id):
print(response["users"][user_id]["id"])
locate_user_id(response, 1)
如果您确实希望获得具有传递的id号的用户,则可以迭代用户列表:
def locate_user_id(response, user_id):
for user in response["users"]:
if user["id"] == user_id:
print(user)
此外,如果您能够重新组织数据,则可以尝试以下方法:
response = {
"users": {
1: "Joe",
2: "Bob",
}
}
这不是有效的Python语法。您应该考虑重新设计代码。这是个糟糕的设计。这里有一些非常糟糕的答案。不要使用
eval
,而是重新设计代码,使您能够通过传递int来访问数据。OP提出了错误的问题(没有意识到),这就是您回答的问题。他/她真正想要的是理解如何从嵌套的数据结构中检索数据;在本例中,如何在列表中搜索包含正确userId propertyNo的元素……OP在其示例代码中具有嵌套的访问符号这一事实意味着他知道。