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

我有一个形式的字典:

[
    {
        "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 JSON对象必须是str,bytes或bytearray,而不是'dict - python

在Python 3中,要加载以前保存的json,如下所示:json.dumps(dictionary)输出是这样的{"('Hello',)": 6, "('Hi',)": 5}当我使用json.loads({"('Hello',)": 6,…

Python:使用两个列表进行字典 - python

如何使用python使用两个列表作为字典list_one_keys = ['key1', 'key2', 'key3', 'key4'] 嵌套列表:list_two_values = [['a1var1', 'a1var2', '…

Python:BeautifulSoup-根据名称属性获取属性值 - python

我想根据属性名称打印属性值,例如<META NAME="City" content="Austin"> 我想做这样的事情soup = BeautifulSoup(f) //f is some HTML containing the above meta tag for meta_tag in soup(&#…

Python uuid4,如何限制唯一字符的长度 - python

在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…

Python:无法识别Pip命令 - python

这是我拍摄的屏幕截图。当我尝试在命令提示符下使用pip时,出现以下错误消息:pip无法识别为内部或外部命令,可操作程序或批处理文件。我已经检查了这个线程:How do I install pip on Windows?我所能找到的就是我必须将"C:\PythonX\Scripts"添加到我的类路径中,其中X代表python版本。如您在我的…