[英]Printing the values in a nested dictionary in Python 2.x
I have a dictionary type variable returned in my Python 2.x script that contains the below values:- 我在我的Python 2.x脚本中返回了一个包含以下值的字典类型变量: -
{u'image': u'/users/me/Desktop/12345_507630509400555_869403269181768452_n.jpg', u'faces': [{u'gender': {u'gender': u'FEMALE', u'score': 0.731059}, u'age': {u'max': 17, u'score': 0.983185}, u'face_location': {u'width': 102, u'top': 102, u'left': 426, u'height': 106}}]}
What I want to do is extract the following values for the given keys:- 我想要做的是为给定的密钥提取以下值: -
I tried the below but it doesn't seem to return what I am looking for: 我尝试了以下但它似乎没有返回我要找的东西:
if key == 'faces':
for k, v in key:
print(k['gender'], k['max'], k['age'][0], k['age'][1])
Any suggestions on how I can access and print the values I am interested in? 关于如何访问和打印我感兴趣的值的任何建议?
You have nested dicts and lists: 你有嵌套的dicts和列表:
d = {u'image': u'/users/me/Desktop/12345_507630509400555_869403269181768452_n.jpg', u'faces': [{u'gender': {u'gender': u'FEMALE', u'score': 0.731059}, u'age': {u'max': 17, u'score': 0.983185}, u'face_location': {u'width': 102, u'top': 102, u'left': 426, u'height': 106}}]}
# iterate over the list of dict(s)
for dct in d["faces"]:
gender, age = dct['gender'], dct["age"]
print(gender["gender"], gender["score"], age["max"], age["score"])
The gender dict looks like: 性别词典看起来像:
{u'gender': u'FEMALE', u'score': 0.731059}
So we use the keys "gender" and "score" to get the values, the age dict looks like: 所以我们使用“性别”和“得分”键来获取值,年龄字典看起来像:
{u'max': 17, u'score': 0.983185}
Again we just grab the values using the keys "max" and "score" 我们再次使用“max”和“score”键来获取值
It's a bit complex dict. 这是一个有点复杂的词典。 This is how you extract the desired values:
这是您提取所需值的方法:
Let d
be your dict: 让
d
成为你的词:
key = 'faces'
inner = d[key][0]
print(inner['gender']['gender'], inner['gender']['score'], inner['age']['max'], inner['age']['score'])
Output: 输出:
FEMALE 0.731059 17 0.983185
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.