如何在Python中动态生成字典数组?

2024-05-18 10:52:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用boto3api自动将分区添加到粘合表中。为了创建一个单独的分区,我可以使用create\u partition api,它要求我指定一个如下所示的字典作为输入。你知道吗

PartitionInput = {
                        'Values': [
                            '2018', '08', '25', '06'
                        ],
                        'StorageDescriptor': {
                            'Location': 'some_location/2018/08/25/06',
                            'InputFormat': 'input_format',
                            'OutputFormat': 'output_format',
                            'SerdeInfo': 'serde_info'
                        }
                    }

现在,我想使用batch\u create\u partition API,在这里我需要指定一个上面的dict数组,以便一起创建多个分区。因此,如果用户输入2018年8月25日(开始日期)和3作为分区数,那么我的数组应该包含3个值,其中每个值都是上面的dict,但是哪个值和位置在变化。所以输出将是-

PartitionInput = [{
    'Values': [
      '2018', '08', '25', '00'
    ],
    'StorageDescriptor': {
      'Location': 'some_location/2018/08/25/06',
      'InputFormat': 'input_format',
      'OutputFormat': 'output_format',
      'SerdeInfo': 'serde_info'
    }
  },
  {
    'Values': [
      '2018', '08', '25', '01'
    ],
    'StorageDescriptor': {
      'Location': 'some_location/2018/08/25/06',
      'InputFormat': 'input_format',
      'OutputFormat': 'output_format',
      'SerdeInfo': 'serde_info'
    }
  }, {
    'Values': [
      '2018', '08', '25', '03'
    ],
    'StorageDescriptor': {
      'Location': 'some_location/2018/08/25/06',
      'InputFormat': 'input_format',
      'OutputFormat': 'output_format',
      'SerdeInfo': 'serde_info'
    }
  }
]

我对python和编程都是新手,所以我不知道该怎么做。你知道吗


Tags: infoformatinputoutputcreatelocationsome分区
1条回答
网友
1楼 · 发布于 2024-05-18 10:52:44

我能用下面的代码解决上面的问题-

for x in range(24):
    year = 2018
    month = 02
    day = 25
    hour = x
    part_loc = "some_location/{}/{}/{}/{}".format(year, month, day, hour)
    input_dict = {
        'Values': [
            str(year), str(month), str(day), str(hour)
        ],
        'StorageDescriptor': {
            'Location': part_loc,
            'InputFormat': 'input_format',
            'OutputFormat': 'output_format',
            'SerdeInfo': 'serde_info'
        }
    }

    input_list.append(input_dict.copy())

print input_list

相关问题 更多 >