【问题标题】:Parsing dictionaries in a JSON file with Python使用 Python 解析 JSON 文件中的字典
【发布时间】:2021-02-11 06:45:01
【问题描述】:

我对 Python 和 JSON 还很陌生,我在解析这些数据时遇到了一些麻烦:

{
  "tests":
  [
    {"array": [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], "target": 163},
    {"array": [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], "target": 164},
    {"array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "target": 18},
    {"array": [-7, -5, -3, -1, 0, 1, 3, 5, 7], "target": -5},
    {"array": [3, 5, -4, 8, 11, 1, -1, 6], "target": 10},
    {"array": [1, 2, 3, 4, 5, 6, 7, 8, 9], "target": 17},
    {"array": [3, 5, -4, 8, 11, 1, -1, 6], "target": 15},
    {"array": [4, 6, 1, -3], "target": 3},
    {"array": [4, 6, 1], "target": 5},
    {"array": [4, 6], "target": 10},
    {"array": [14], "target": 15},
    {"array": [15], "target": 15}
  ]
}

这是文件内部的内容,如果我理解正确,这是一个字典(“测试”:),其中包含以逗号分隔的字典,其中每个字典都有一个 kvp 数组:列表,目标:int。如果我在这部分错了,请纠正我。

现在,我要做的是遍历每个字典并打印列表,然后打印每个字典的整数。到目前为止,这就是我在 Python 中所拥有的:

for array, target_sum in test_data['tests']:
    print(array, target_sum)

但我打印出来的只是这个:

数组目标 数组目标 数组目标 数组目标 数组目标 数组目标 数组目标 数组目标 数组目标 数组目标 数组目标 数组目标

我想我想问的是如何打印 this 的值而不是键。任何帮助表示赞赏,对于菜鸟问题​​感到抱歉。

【问题讨论】:

  • 'tests' 是它所在字典的关键字,并且为该关键字分配了一个字典列表,每个字典都包含两个关键字和值

标签: python json loops dictionary


【解决方案1】:

确实,您打印的是键名而不是值!

要打印值,请执行以下操作:

for test in test_data['tests']:
    print(test['array'], test['target'])

它给出:

[-21, 301, 12, 4, 65, 56, 210, 356, 9, -47] 163
[-21, 301, 12, 4, 65, 56, 210, 356, 9, -47] 164
[1, 2, 3, 4, 5, 6, 7, 8, 9, 15] 18
[-7, -5, -3, -1, 0, 1, 3, 5, 7] -5
[3, 5, -4, 8, 11, 1, -1, 6] 10
[1, 2, 3, 4, 5, 6, 7, 8, 9] 17
[3, 5, -4, 8, 11, 1, -1, 6] 15
[4, 6, 1, -3] 3
[4, 6, 1] 5
[4, 6] 10
[14] 15
[15] 15

【讨论】:

  • 正是我想要的!谢谢。
【解决方案2】:

也许是这样的?

import json

data = '''\
{
  "tests":
  [
    {"array": [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], "target": 163},
    {"array": [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], "target": 164},
    {"array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "target": 18},
    {"array": [-7, -5, -3, -1, 0, 1, 3, 5, 7], "target": -5},
    {"array": [3, 5, -4, 8, 11, 1, -1, 6], "target": 10},
    {"array": [1, 2, 3, 4, 5, 6, 7, 8, 9], "target": 17},
    {"array": [3, 5, -4, 8, 11, 1, -1, 6], "target": 15},
    {"array": [4, 6, 1, -3], "target": 3},
    {"array": [4, 6, 1], "target": 5},
    {"array": [4, 6], "target": 10},
    {"array": [14], "target": 15},
    {"array": [15], "target": 15}
  ]
}
'''

d = json.loads(data)
for test in d['tests']:
    print(sum(test['array']), test['target'])

【讨论】:

    【解决方案3】:

    这是你必须做的:

    for item in a['tests']:
        print(item['array'], '----', item['target'])
    

    为您提供以下输出:

    [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47] ---- 163
    [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47] ---- 164
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 15] ---- 18
    [-7, -5, -3, -1, 0, 1, 3, 5, 7] ---- -5
    [3, 5, -4, 8, 11, 1, -1, 6] ---- 10
    [1, 2, 3, 4, 5, 6, 7, 8, 9] ---- 17
    [3, 5, -4, 8, 11, 1, -1, 6] ---- 15
    [4, 6, 1, -3] ---- 3
    [4, 6, 1] ---- 5
    [4, 6] ---- 10
    [14] ---- 15
    [15] ---- 15
    

    【讨论】:

      【解决方案4】:

      代码可能如下所示:

      tests = [
          {"array": [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], "target": 163},
          {"array": [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], "target": 164},
          {"array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "target": 18},
          {"array": [-7, -5, -3, -1, 0, 1, 3, 5, 7], "target": -5},
          {"array": [3, 5, -4, 8, 11, 1, -1, 6], "target": 10},
          {"array": [1, 2, 3, 4, 5, 6, 7, 8, 9], "target": 17},
          {"array": [3, 5, -4, 8, 11, 1, -1, 6], "target": 15},
          {"array": [4, 6, 1, -3], "target": 3},
          {"array": [4, 6, 1], "target": 5},
          {"array": [4, 6], "target": 10},
          {"array": [14], "target": 15},
          {"array": [15], "target": 15}
        ]
      
      
      for dictionary in tests:
          for _, value in dictionary.items():
              print(value)
      

      所以在你的情况下,我将tests 列了一个列表,因为没有必要将它存储在 dict() 中。然后我遍历该列表中的每个字典,对于每个字典,我得到了键 _(下划线),这是一个一次性变量(我们将不再使用它)和值并将其打印出来。 (dictionary.items() 会返回所有关键字和它们的值)

      【讨论】:

        【解决方案5】:

        主要的大字典有一个关键的“测试”。这个键的值是一个列表。该列表包含带有键 arraytarget 的字典。 array 的值是整数列表。 target 是一个整数。假设你在一个字符串中有这个 json。

        json_str = """{
          "tests":
          [
            {"array": [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], "target": 163},
            {"array": [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], "target": 164},
            {"array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "target": 18},
            {"array": [-7, -5, -3, -1, 0, 1, 3, 5, 7], "target": -5},
            {"array": [3, 5, -4, 8, 11, 1, -1, 6], "target": 10},
            {"array": [1, 2, 3, 4, 5, 6, 7, 8, 9], "target": 17},
            {"array": [3, 5, -4, 8, 11, 1, -1, 6], "target": 15},
            {"array": [4, 6, 1, -3], "target": 3},
            {"array": [4, 6, 1], "target": 5},
            {"array": [4, 6], "target": 10},
            {"array": [14], "target": 15},
            {"array": [15], "target": 15}
          ]
        }"""
        

        要解析这个字典,做

        j_dict = json.loads(json_str)
        

        现在,j_dict['tests'] 为您提供键 tests 中的 ,这是一个列表。试试吧

        print(j_dict['tests'])
        

        您想遍历此列表,并打印列表中每个元素arraytarget 键的值。

        for elem_in_list in j_dict['tests']:
            # Now each elem_in_list is a dict like so:
            # {"array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "target": 18}
            print(elem_in_list['array'], elem_in_list['target'])
        

        这给出了输出

        [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47] 163
        [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47] 164
        [1, 2, 3, 4, 5, 6, 7, 8, 9, 15] 18
        [-7, -5, -3, -1, 0, 1, 3, 5, 7] -5
        [3, 5, -4, 8, 11, 1, -1, 6] 10
        [1, 2, 3, 4, 5, 6, 7, 8, 9] 17
        [3, 5, -4, 8, 11, 1, -1, 6] 15
        [4, 6, 1, -3] 3
        [4, 6, 1] 5
        [4, 6] 10
        [14] 15
        [15] 15
        

        现在,如果您想遍历 array 键中的每个元素,您只需这样做。假设你想取这些元素的平方和,并检查它是否等于target

        for elem_in_list in j_dict['tests']:
            # Now each elem_in_list is a dict like so:
            # {"array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "target": 18}
            elem_array = elem_in_list['array']
            elem_target = elem_in_list['target']
            total = 0
            for x in elem_array:
                total += x**2
            if elem_target == total:
                print("Equal!")
            else:
                print("Not equal!")
        

        【讨论】:

          【解决方案6】:

          我不知道这是否是最pythonic的方式,或者即使它会起作用,但你可以试试这个(只是为了打印最后询问的数据):

          for array, target_sum in test_data['tests']:
              print(test_data['tests'].get(array), test_data['tests'].get(target_sum))
          

          【讨论】:

            猜你喜欢
            • 2019-01-18
            • 2021-11-04
            • 1970-01-01
            • 2021-12-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-04-02
            相关资源
            最近更新 更多