我是机器人和 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。由于键是字符串,因此需要正确引用它们。这是文档中的相关部分:
- 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/