Python在JSON结构中获取同级

时间:2019-02-10 17:20:21

标签: python json dictionary

假设我获得了 目标 ,并希望获得 目标 。您将如何遍历此过程,并在一口衬管中获得所需的目标值(例如A1)。我使用json.load(json_data)

从文件中获取数据没有问题

JSON

{
  "conservative": {
    "goal": "A1",
    "target" : 60000,
    "oneoff": 6000,
    "regular": 600
  },
  "moderate": {
    "goal": "A2",
    "target": 70000,
    "oneoff": 7000,
    "regular": 710
  },
  "optimistic": {
    "goal": "A3",
    "target": 80000,
    "oneoff": 8000,
    "regular": 800
  }
}

3 个答案:

答案 0 :(得分:3)

也许您可以尝试使用以下命令获取可能与输入值匹配的目标列表(如果期望使用单个值,您可以简单地输入 [0] 从列表)。例如。与goal_val = 'A1'

target = [val['target'] for _, val in my_data.items() if val['goal'] == goal_val]

答案 1 :(得分:2)

这是一个简单的单行解决方案:

d = {
  "conservative": {
    "goal": "A1",
    "target" : 60000,
    "oneoff": 6000,
    "regular": 600
  },
  "moderate": {
    "goal": "A2",
    "target": 70000,
    "oneoff": 7000,
    "regular": 710
  },
  "optimistic": {
    "goal": "A3",
    "target": 80000,
    "oneoff": 8000,
    "regular": 800
  }
}

goal = "A1" # <-- Your goal here

target = next(v['target'] for _, v in d.items() if v['goal'] == goal)
# target == 60000

这使用生成器表达式来避免执行不必要的迭代。 next()将确保您只返回一个值。

可以很容易地将其修改为返回完整的匹配字典:

match = next(v for k, v in d.items() if v['goal'] == goal)
# match == {"goal": "A1", target: 60000, ...}

答案 2 :(得分:1)

在下面的代码中,我的朋友:

data = {
  "conservative": {
    "goal": "A1",
    "target" : 60000,
    "oneoff": 6000,
    "regular": 600
  },
  "moderate": {
    "goal": "A2",
    "target": 70000,
    "oneoff": 7000,
    "regular": 710
  },
  "optimistic": {
    "goal": "A3",
    "target": 80000,
    "oneoff": 8000,
    "regular": 800
  }
}

goal_required = 'A1'

for obj in data:
    if data[obj]['goal'] == goal_required:
        target = data[obj]['target']
        print("Object {} with the goal {} needs a target of {}".format(obj, goal_required, target))

哪个给出输出:

Object conservative with the goal A1 needs a target of 60000