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

标签 python dictionary robotframework

我是机器人和 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']}       

关于python - 如何从嵌套字典中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40052885/

相关文章:

python - 重新启动游戏(重置滚动屏幕)

python - 我应该在哪里导入 urllib2 来上课?

python - 使用 Python 的 numpy 实现随机梯度下降

ios - 在单例类中追加数组并在另一个 Controller 中计数返回 0

python - 如何通过进程名获取PID?

swift - 如何更新混合类型的 Swift 字典值,尤其是数组

python字典列总和

python - 使用 selenium2library 设置自动下载首选项配置文件

selenium - 如何在 Robot Framework 中执行 JavaScript

java - RobotFramework 中的嵌套循环