我有以下JSON字典。 我想要做的是删除“orbiting_body”不是“地球”的所有“close_approach_data”对象。 问题是orbiting_body可能有多个对象:“Earth”,在所有这些对象之间我试图保持最小的“approach_date”。
data = [
{
"id": "01",
"close_approach_data": [
{
"orbiting_body": "Earth",
"approach_date": "1945-06-07"
},
{
"orbiting_body": "Earth",
"approach_date": "1975-06-07"
},
{
"orbiting_body": "Mars",
"approach_date": "1935-06-07"
}
]
},
{
"id": "02",
"close_approach_data": [
{
"orbiting_body": "Earth",
"approach_date": "1945-06-07"
},
{
"orbiting_body": "Earth",
"approach_date": "1975-06-07"
},
{
"orbiting_body": "Mars",
"approach_date": "1935-06-07"
}
]
}
]
我希望得到这个:
data = [
{
"id": "01",
"close_approach_data": {
"orbiting_body": "Mars",
"approach_date": "1935-06-07"
}
},
{
"id": "02",
"close_approach_data": {
"orbiting_body": "Mars",
"approach_date": "1935-06-07"
}
}
]
所以我想提出一些代码:
earthObjs =[]
for element in data:
for subel in element["close_approach_data"]:
if ([subel][0]["orbiting_body"]=="Earth"):
#then i would have to store the objects
earthObjs.append([subel])
#here i am trying to find the object with the min 'approach_date'
minEarth = min(dt.strptime(earthObjs["close_approach_date"],"%Y-%m-%d"))
#then i would have to somehow place this as the only element of close_approach_data
element["close_approach_data"] = json.loads(minEarth)
#and clear the earthObjs list so it can be used for the next element
earthObjs.clear()
我非常清楚我的一半代码不起作用。我想我可能最终会接近它的工作,我真的需要一些帮助。具体来说,我知道在搜索min时我做错了,因为我无法访问对象的'close_approach_data'
字段。
另外,我也不确定json.load
s行。
答案 0 :(得分:1)
以下是您将描述的处理代码直接转换为代码:
$username =
输出:
from datetime import datetime
import json
for dataset in data:
earliest, initial = datetime.max, {}
# Find the non-Earth body with the earliest approach date.
for close_approach in dataset["close_approach_data"]:
if close_approach["orbiting_body"] != "Earth":
dt = datetime.strptime(close_approach["approach_date"],
"%Y-%m-%d")
if dt < earliest:
dt, initial = earliest, close_approach
# Replace entire close_approach_data list with a single object
# comprised of the non-Earth item with the earliest date (or an
# empty dictionary if there weren't any).
dataset["close_approach_data"] = initial
print(json.dumps(data, indent=4))
答案 1 :(得分:0)
这是实现算法的一种方法:
res = []
for d in data:
res.append({**{'id': d['id'], **{'close_approch_data': \
next((iter(sorted((e for e in d['close_approach_data'] \
if e['orbiting_body'] != 'Earth'), \
key=lambda x: x['approach_date']))), None)}}})
print(res)
[{'close_approch_data': {'approach_date': '1935-06-07',
'orbiting_body': 'Mars'},
'id': '01'},
{'close_approch_data': {'approach_date': '1935-06-07',
'orbiting_body': 'Mars'},
'id': '02'}]
<强>解释强>
乍一看(和第二次),这看起来像一团糟。但关键部分是:id
,请将项目附加到列表res
。if
子句包含非来自地球的数据。datetime
,但根据当前格式,这不是必需的。next(iter(...))
提取第一个元素(如果它存在)。如果不存在任何元素,请返回{'close_approach_data': None}
。