Skip to main content
 首页 » 编程设计

python之如何从嵌套字典中获取值

2024年10月17日7qq号

我是机器人和 Python 的新手。我有一个嵌套字典,我需要从中获取值,但我无法访问它们。

${result} =  Get Info  from_here=location  mode=aggregate 
@{keys}=    Get Dictionary Keys    ${result} 
${robot_dict}=    Create Dictionary 
:FOR    ${key}    IN    @{keys} 
    \    Set To Dictionary    ${robot_dict}    ${key}=${result['${key}']} 
Log Many  ${robot_dict} 
######Output from robot_dict is: 
#{'Name1':  
#       {'nickname':  
#           {'Name': 'Name1', 'FirstName': 'Full', 'Boy':  
#               {'Age': 'N/A', 'Single': '0'},  
#               'Girl':  
#               {'Height': '229057', 'Weight': 'N/A'} 
#           } 
#       },  
#'Name2':{'nickname':  
#           {'Name': 'Name2', 'FirstName': 'Full', 'Boy':  
#               {'raw_pkt_count': '229059', 'Age': 'N/A'},  
#               'Girl':  
#               {'Height': '0', 'Weight': 'N/A'} 
#           } 
#       } 
#} 
############# 

试过这个:

${current_key} =  Get Dictionary Keys  ${robot_dict[Name1][nickname][Girl][Height]}        
######Error: Resolving variable '${robot_dict[Name1][nickname][Girl][Height]}' failed: KeyError: 0          

还有这个:

${current_key} =  Get Dictionary Keys  ${robot_dict}    Name1.nickname.Girl.Height    
#######Error: Dictionary does not contain key Name1.nickname.Girl.Height 

请您参考如下方法:

当您使用 extended variable syntax 时,您必须将代码视为 python。由于键是字符串,因此需要正确引用它们。这是文档中的相关部分:

  1. The expression inside the curly brackets is evaluated as a Python expression, so that the base variable name is replaced with its value. If the evaluation fails because of an invalid syntax or that the queried attribute does not exist, an exception is raised and the test fails.
${current_key} =  Get Dictionary Keys  ${robot_dict['Name1']['nickname']['Girl']['Height']}