问题描述
你怎么拉,分割,并追加字典里面的字典里的数组?
How do you pull, split, and append an array inside a dictionary inside a dictionary?
这是我已经得到了数据:
This is the data I've got:
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"]
}]
}
}
这是我所需要的 -
This is what I need --
{
"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"
}
}
}
下面是我在那里只是玩了,完全失去了!!
Here is where I was just playing around with it and totally lost!!
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"]:
...并完全失去了
...and totally lost
推荐答案
这个怎么样?
#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)
这将与您所显示的数据结构的工作,但并不一定与各种嵌套的数据,因为我们做的属性的浅拷贝。这将意味着你必须确保除了值
列表,它仅包含像数字,字符串或布尔原子值。值列表可以包含嵌套结构,因为我们唯一的运动引用那里。
This will work with the data structure you've shown, but not necessarily with all kinds of nested data, since we do a shallow copy of the attribute. That will mean that you have to make sure that apart from the "value"
list, it only contains atomic values like numbers, strings, or booleans. The values list may contain nested structures, since we're only moving references there.
这篇关于Python字典/ JSON成立的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!