如何从列表中提取值并将其存储为字典(键值对)?

我需要从此字典列表中提取2个值,并将其存储为键值对。 在这里,我附加了示例数据。在这里,我需要从此输入中提取“名称”和“服务”,并将其存储为字典。其中“名称”是键,相应的“服务”是它的值。

输入:

response  = {
'Roles': [
    {
        'Path': '/','Name': 'Heera','Age': '25','Policy': 'Policy1','Start_Month': 'January','PolicyDocument': 
            {
                'Date': '2012-10-17','Statement': [
                    {
                        'id': '','RoleStatus': 'New_Joinee','RoleType': {
                                'Service': 'Service1'
                                 },'action': ''
                    }
                ]
            },'Duration': 3600
    },{
        'Path': '/','Name': 'Prem','Age': '40','Policy': 'Policy2','Start_Month': 'April','PolicyDocument': 
            {
                'Date': '2018-11-27','RoleStatus': 'Senior','RoleType': {
                                'Service': ''
                                 },'Duration': 2600
    },]
}

从此输入中,我需要将输出作为字典类型。

输出格式: {名称:服务}

输出:

{ "Heera":"Service1","Prem" : " "}

我的尝试:

Role_name =[]
response = {#INPUT WHICH I SPECIFIED ABOVE#}
roles = response['Roles']
for role in roles:
    Role_name.append(role['Name'])
print(Role_name)

我需要将名称与其相应的服务配对。任何帮助都是非常可观的。

谢谢。

iCMS 回答:如何从列表中提取值并将其存储为字典(键值对)?

您只需要这样做:

liste = []
for role in response['Roles']:
    liste.append(
            {
                role['Name']:role['PolicyDocument']['Statement'][0]['RoleType']['Service'],}
            )
print(liste)
,

似乎您的输入数据的结构有点奇怪,我不确定)接下来的几个月在做什么,因为它们会使事情变得无效,但这是一个工作脚本,假设您从输入中删除了括号。

response = {
    'Roles': [
        {
            'Path': '/','Name': 'Heera','Age': '25','Policy': 'Policy1','Start_Month': 'January','PolicyDocument':
{
    'Date': '2012-10-17','Statement': [
        {
            'id': '','RoleStatus': 'New_Joinee','RoleType': {
                'Service': 'Service1'
            },'Action': ''
        }
    ]
},'Duration': 3600
},{
    'Path': '/','Name': 'Prem','Age': '40','Policy': 'Policy2','Start_Month': 'April','PolicyDocument':
{
    'Date': '2018-11-27','RoleStatus': 'Senior','RoleType': {
                'Service': ''
            },'Duration': 2600
},]
}

output = {}

for i in response['Roles']:
    output[i['Name']] = i['PolicyDocument']['Statement'][0]['RoleType']['Service']

print(output)

,

您只需要写一条长行就可以到达键“ Service”。 并且您在 Start_Month':'January')'Start_Month':'April')中出现了语法错误。您不能有一个未封闭的括号。 对其进行修复,然后运行以下命令。

这是代码:

output_dict = {}
for r in response['Roles']:
    output_dict[r["Name"]] = r['PolicyDocument']['Statement'][0]['RoleType']['Service']

print(output_dict)

输出:

{'Heera': 'Service1','Prem': ''}
,

这应该在名为role_services的变量中为您提供所需的内容:

role_services = {}

for role in response['Roles']:
    for st in role['PolicyDocument']['Statement']:
        role_services[role['Name']] = st['RoleType']['Service']

这将确保您可以遍历该数据结构中的所有语句,但是请注意,遍历响应时,如果键值对存在多个条目中,则会覆盖它们!

A reference on for loops可能会有用,它说明了在其中使用if语句的情况,这可以帮助您扩展此语句以检查是否已存在项!

希望有帮助

本文链接:https://www.f2er.com/1966545.html

大家都在问