gpt4 book ai didi

python - 如何合并具有重复值的字典列表以创建嵌套字典?

转载 作者:行者123 更新时间:2023-12-04 23:35:30 27 4
gpt4 key购买 nike

我有一个形式的字典:

[
{
"group_name": "CUSTOMER_RED",
"interface": "ae4",
"unit_name": 2520
},
{
"group_name": "CUSTOMER_RED",
"interface": "ae4",
"unit_name": 4091
},
{
"group_name": "CUSTOMER_BLUE",
"interface": "ae4",
"unit_name": 847
},
{
"group_name": "CUSTOMER_BLUE",
"interface": "ae4",
"unit_name": 103
}
}

我怎样才能将它合并成一个列表,如:

[
{
"group_name": "CUSTOMER_RED",
"interface": "ae4",
"unit_names": [2520, 4091]
},
{
"group_name": "CUSTOMER_BLUE",
"interface": "ae4",
"unit_names": [847, 103]
},
}

或者如果更简单:

[
{
"group_name": "CUSTOMER_RED",
"interfaces": ["ae4": "unit_names": [2520, 4091]]
},
{
"group_name": "CUSTOMER_BLUE",
"interface": ["ae4": "unit_names": [847, 103]]
},
}

我试过这个:

def merge_relevant_config(config):
return_config = []
for item in config:
name = item['group_name']
interface = item['interface']
units = []
for item in config:
if item['group_name'] == name and item['interface'] == interface:
units.append(item['unit_name'])
return_config.append({
'name': name,
'interface': interface,
'units': units
})
return return_config

但是这会返回重复项:

[
{
"name": "CUSTOMER_RED",
"interface": "ae4",
"units": [
2520,
4091
]
},
{
"name": "CUSTOMER_RED",
"interface": "ae4",
"units": [
2520,
4091
]
},
{
"name": "CUSTOMER_BLUE",
"interface": "ae4",
"units": [
847,
103
]
},
{
"name": "CUSTOMER_BLUE",
"interface": "ae4",
"units": [
847,
103
]
}
]

最佳答案

这是一种方法。

例如:

data = [
{
"group_name": "CUSTOMER_RED",
"interface": "ae4",
"unit_name": 2520
},
{
"group_name": "CUSTOMER_RED",
"interface": "ae4",
"unit_name": 4091
},
{
"group_name": "CUSTOMER_BLUE",
"interface": "ae4",
"unit_name": 847
},
{
"group_name": "CUSTOMER_BLUE",
"interface": "ae4",
"unit_name": 103
}
]

result = {}
for i in data:
if i['group_name'] not in result:
#if group by `group_name` & `interface` use --> result[(i['group_name'], i['interface'])]
result[i['group_name']] = {'group_name': i['group_name'], 'interface': i['interface'], "unit_names": [i['unit_name']]}
else:
result[i['group_name']]["unit_names"].append(i['unit_name'])

print(list(result.values()))

输出:

[
{
'group_name': 'CUSTOMER_RED',
'interface': 'ae4',
'unit_names': [2520, 4091]
},
{
'group_name': 'CUSTOMER_BLUE',
'interface': 'ae4',
'unit_names': [847, 103]
}
]

关于python - 如何合并具有重复值的字典列表以创建嵌套字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59105577/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com