python字典/json

2024-06-07 22:37:47 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在字典中的字典中提取、拆分和附加数组?你知道吗

这是我得到的数据:

data = {
    "Event":{
        "distribution":"0",
        "orgc":"Oxygen",
        "Attribute": [{
            "type":"ip-dst",
            "category":"Network activity",
            "to_ids":"true",
            "distribution":"3",
            "value":["1.1.1.1","2.2.2.2"]
        }, {
            "type":"url",
            "category":"Network activity",
            "to_ids":"true",
            "distribution":"3",
            "value":["msn.com","google.com"]
        }]
    }
}

这就是我需要的--

{
    "Event": {
        "distribution": "0",
        "orgc": "Oxygen",
        "Attribute": [{
                "type": "ip-dst",
                "category": "Network activity",
                "to_ids": "true",
                "distribution": "3",
                "value": "1.1.1.1"
            }, {
                "type": "ip-dst",
                "category": "Network activity",
                "to_ids": "true",
                "distribution": "3",
                "value": "2.2.2.2"
            }, {
                "type": "url",
                "category": "Network activity",
                "to_ids": "true",
                "distribution": "3",
                "value": "msn.com"
            }, {
                "type": "url",
                "category": "Network activity",
                "to_ids": "true",
                "distribution": "3",
                "value": "google.com"
            }
        }
    }

在这里,我只是在玩它,完全失去了!!你知道吗

for item in data["Event"]["Attribute"]:
    if "type":"ip-dst" and len("value")>1:
        if 'ip-dst' in item["type"] and len(item["value"])>1:
            for item in item["value"]:

…完全迷路了


Tags: toipcomeventtrueidsvaluetype
1条回答
网友
1楼 · 发布于 2024-06-07 22:37:47

这个怎么样?你知道吗

#get reference to attribute dict
attributes = data["Event"]["Attribute"]
#in the event dictionary, replace it with an empty list
data["Event"]["Attribute"] = []

for attribute in attributes:
    for value in attribute["value"]:
        #for every value in every attribute, copy that attribute
        new_attr = attribute.copy()
        #set the value to that value
        new_attr["value"] = value
        #and append it to the attribute list
        data["Event"]["Attribute"].append(new_attr)

这将适用于您所展示的数据结构,但不一定适用于所有类型的嵌套数据,因为我们只做属性的浅拷贝。这意味着您必须确保除了"value"列表之外,它只包含原子值,如数字、字符串或布尔值。值列表可能包含嵌套结构,因为我们只在其中移动引用。你知道吗

相关问题 更多 >

    热门问题