[英]How to access values from a dictionary inside a list based on another key-value pair?
[英]How to extract values from list and store it as dictionary(key-value pair)?
我需要从这个字典列表中提取 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',
'Statement': [
{
'id': '',
'RoleStatus': 'Senior',
'RoleType': {
'Service': ''
},
'Action': ''
}
]
},
'Duration': 2600
},
]
}
从这个输入中,我需要 output 作为字典类型。
Output 格式: {名称:服务}
Output:
{ "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)
我需要将名称与其相应的服务配对。 任何帮助都会非常显着。
提前致谢。
你只需要这样做:
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',
'Statement': [
{
'id': '',
'RoleStatus': 'Senior',
'RoleType': {
'Service': ''
},
'Action': ''
}
]
},
'Duration': 2600
},
]
}
output = {}
for i in response['Roles']:
output[i['Name']] = i['PolicyDocument']['Statement'][0]['RoleType']['Service']
print(output)
你只需要写一条长线,直到关键的“服务”。 你在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)
Output:
{'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']
它将确保您将 go 通过该数据结构中的所有语句,但请注意,您将在遍历响应时覆盖键值对,如果它们存在于多个条目中!
可能有帮助的 for 循环的参考,说明了在其中使用if
语句,这可以帮助您扩展它以检查项目是否已经存在!
希望有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.