【问题标题】:How to dynamically generate array of dictionary in Python?如何在 Python 中动态生成字典数组?
【发布时间】:2019-01-31 23:31:56
【问题描述】:

我正在使用 boto3 API 自动将分区添加到粘合表。为了创建一个单独的分区,我可以使用 create_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_create_partition API,我需要指定一个上述 dict 的数组来一起创建多个分区。因此,如果用户输入 2018 年 8 月 25 日(开始日期)和 3 作为分区数,那么我的数组应该包含 3 个值,其中每个值都是上述字典,但值和位置会发生变化。所以输出将是 -

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 和编程新手,所以我不知道该怎么做。

【问题讨论】:

    标签: python arrays python-2.7 dictionary boto3


    【解决方案1】:

    我能够使用以下代码解决上述问题 -

    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
    

    【讨论】:

      猜你喜欢
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 2020-11-14
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      相关资源
      最近更新 更多