【问题标题】:python dictionary/json inceptionpython字典/json初始
【发布时间】:2016-03-07 07:30:45
【问题描述】:

如何在字典中拉取、拆分和追加数组?

这是我得到的数据:

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"]:

...完全迷失了

【问题讨论】:

  • 除了标签,有什么区别?
  • 不知道你在这里问什么。 “得到”和“需要”看起来像同一个结构。您是否正在尝试将 dict 转换为 json?
  • @MadWombat OP 正试图从组合的 "attribute" 值变为单个值。

标签: python arrays json dictionary


【解决方案1】:

这个怎么样?

#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" 列表之外,它只包含原子值,如数字、字符串或布尔值。值列表可能包含嵌套结构,因为我们只是在其中移动引用。

【讨论】:

    猜你喜欢
    • 2012-04-27
    • 2017-11-15
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2022-01-24
    • 2013-03-27
    相关资源
    最近更新 更多