Python - 将嵌套项添加到一个嵌套列表
Posted
技术标签:
【中文标题】Python - 将嵌套项添加到一个嵌套列表【英文标题】:Python - Add nested items to one nested list 【发布时间】:2022-01-20 23:21:06 【问题描述】:我正在尝试创建一个名为 Results 的嵌套 Python 字典。
我正在使用 AWS Rekognition 获取图像并输出结果。
results_dict 编译后只包含一个结果,我希望将所有结果放在一个嵌套循环中
我想得到:
"Results": [
"Name": "Human",
"Confidence": 98.87621307373047,
,
"Name": "Face",
"Confidence": 98.87621307373047,
,
"Name": "Person",
"Confidence": 98.87621307373047,
,
]
但我得到:
'Results':
'Name': 'Paper',
'Confidence': 57.299766540527344
代码正在替换文本,我想添加另一组名称和置信度。
我的代码是:
import boto3
import json
BUCKET = "*****"
FOLDER = 'testing/'
JOEY = FOLDER + "Joey_30_Sept.png"
BEYONCE = FOLDER + "beyonce_rekognition_moderation_testing.jpg"
MANBEARD = FOLDER + "man_beard.jpg"
MEN = FOLDER + "men_group.jpg"
client = boto3.client('rekognition')
response = client.detect_labels(Image=
'S3Object':
'Bucket': BUCKET,
'Name': JOEY
,
MaxLabels = 10,
MinConfidence=0)
results_dict =
results_dict['Results'] =
results_dict['Results']['Name'] = ""
results_dict['Results']['Confidence'] = ""
for label in response['Labels']:
name = label['Name'] #to get the whole bounding box.
confidence = label['Confidence']
name_str = str(name)
conf_str = str(confidence)
results_dict["Results"]["Name"] = label['Name']
results_dict["Results"]["Confidence"] = label['Confidence']
print(results_dict)
【问题讨论】:
【参考方案1】:您将results_dict['Results']
定义为字典而不是字典列表:
...
results_dict =
results_dict['Results'] = []
results_dict['Results']['Name'] = ""
results_dict['Results']['Confidence'] = ""
for label in response['Labels']:
name = label['Name'] #to get the whole bounding box.
confidence = label['Confidence']
name_str = str(name)
conf_str = str(confidence)
results_dict['Results'].append(["Name": name_str, "Confidence": conf_str )
print(results_dict)
【讨论】:
完美!谢谢你。我整天都在不停地写代码。我需要另一双眼睛才能看到错误。谢谢。以上是关于Python - 将嵌套项添加到一个嵌套列表的主要内容,如果未能解决你的问题,请参考以下文章