Python - 将字典和键值列表转换为字符串

标签 python string list dictionary google-deployment-manager

获取以下字典和键值对列表:

              [{'name': 'test-project',
                'properties': {'name': 'test-project',
                               'parent': {'id': '', 'type': 'folder'},
                               'projectId': 'test-project'},
                'type': 'cloudresourcemanager.v1.project'},
               {'metadata': {'dependsOn': ['test-project']},
                'name': 'billing_test-project',
                'properties': {'billingAccountName': 'billingAccountName',
                               'name': 'projects/test-project'},
                'type': 'deploymentmanager.v2.virtual.projectBillingInfo'},
               {'name': 'apis',
                'properties': {'apis': ['compute.googleapis.com'],
                               'billing': 'billing_test-project',
                               'concurrent_api_activation': True,
                               'project': 'test-project'},
                'type': 'apis.py'},
               {'name': 'service-accounts',
                'properties': {'project': 'test-project',
                               'service-accounts': ''},
                'type': 'service-accounts.py'},
               {'action': 'gcp-types/compute-v1:compute.projects.setUsageExportBucket',
                'metadata': {'dependsOn': ['test-project',
                                           'test-project-compute.googleapis.com']},
                'name': 'set-export-bucket',
                'properties': {'bucketName': 'gs://usage-exports',
                               'project': 'test-project',
                               'reportNamePrefix': 'usage_gce_'}}]}

我需要将其转换为以下语法:

资源:\n- 名称:测试项目\n 属性:\n 名称:测试项目\n 父级:\n id:\n 类型:文件夹\n

我想,在我简短的 Google 搜索之后,也许类似下面的内容会起作用:

'\n'.join(d for d in resources)

不幸的是,这给了我错误: “类型错误:序列项 0:预期的 str 实例,找到字典”

任何有关此问题的帮助将不胜感激。

(顺便说一句,Google 配置内容作为字符串的唯一示例是用于创建 VM: https://cloud.google.com/deployment-manager/docs/deployments#api ;我注意到空格似乎随着每个键值对而增加,但我不完全确定如果这里确实需要的话)。

编辑: 抱歉,我的意思是说我需要与下面类似的格式的键值对,作为字符串:

resource = "resources:\n- name: vm-created-by-cloud-config\n  type: compute.v1.instance\n  properties:\n    zone: us-central1-a\n    machineType: https://www.googleapis.com/compute/v1/projects/myproject/zones/us-central1-a/machineTypes/n1-standard-1\n    disks:\n    - deviceName: boot\n      type: PERSISTENT\n      boot: true\n      autoDelete: true\n      initializeParams:\n        diskName: disk-created-by-cloud-config\n        sourceImage: https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20151104\n    networkInterfaces:\n    - network: https://www.googleapis.com/compute/v1/projects/myproject/global/networks/default\n"

所以,打印时,它看起来像这样:

resources:
- name: test-project
  properties:
    name: test-project
    parent:
      id:
      type: folder
    projectId: test-project
  type: cloudresourcemanager.v1.project
- metadata:
    dependsOn: test-project
  name: billing_test-project
  properties:
    billingAccountName: billingAccountName
    name: projects/test-project
  type: deploymentmanager.v2.virtual.projectBillingInfo
- name: apis
  properties:
    apis: compute.googleapis.com
    billing: billing_test-project
    concurrent_api_activation: True
    project: test-project
  type: apis.py
- name: service-accounts
  properties:
    project: test-project
    service-accounts:
  type: service-accounts.py
- action: gcp-types/compute-v1:compute.projects.setUsageExportBucket
  metadata:
    dependsOn: test-project,test-project-compute.googleapis.com
  name: set-export-bucket
  properties:
    bucketName: gs://usage-exports
    project: test-project
    reportNamePrefix: usage_gce_

最佳答案

尝试应用以下递归函数。这应该适用于您的特定用例:

resources = {'resources': [{'name': 'test-project',
                'properties': {'name': 'test-project',
                               'parent': {'id': '', 'type': 'folder'},
                               'projectId': 'test-project'},
                'type': 'cloudresourcemanager.v1.project'},
               {'metadata': {'dependsOn': ['test-project']},
                'name': 'billing_test-project',
                'properties': {'billingAccountName': 'billingAccountName',
                               'name': 'projects/test-project'},
                'type': 'deploymentmanager.v2.virtual.projectBillingInfo'},
               {'name': 'apis',
                'properties': {'apis': ['compute.googleapis.com'],
                               'billing': 'billing_test-project',
                               'concurrent_api_activation': True,
                               'project': 'test-project'},
                'type': 'apis.py'},
               {'name': 'service-accounts',
                'properties': {'project': 'test-project',
                               'service-accounts': ''},
                'type': 'service-accounts.py'},
               {'action': 'gcp-types/compute-v1:compute.projects.setUsageExportBucket',
                'metadata': {'dependsOn': ['test-project',
                                           'test-project-compute.googleapis.com']},
                'name': 'set-export-bucket',
                'properties': {'bucketName': 'gs://usage-exports',
                               'project': 'test-project',
                               'reportNamePrefix': 'usage_gce_'}}]}


def unpack_dict(d, spaces=0):
    try:
        s = ' ' * spaces
        spaces += 2
        return  ' '.join([f'\n{s}{k}: {unpack_dict(v, spaces)}' for k, v in d.items()])
    except AttributeError:
        if isinstance(d, list):
            return ''.join([unpack_dict(item) for item in d])
        else:
            return d


result = unpack_dict(resources).strip()

输出打印(结果)

resources: 
name: test-project 
properties: 
  name: test-project 
  parent: 
    id:  
    type: folder 
  projectId: test-project 
type: cloudresourcemanager.v1.project
metadata: 
  dependsOn: test-project 
name: billing_test-project 
properties: 
  billingAccountName: billingAccountName 
  name: projects/test-project 
type: deploymentmanager.v2.virtual.projectBillingInfo
name: apis 
properties: 
  apis: compute.googleapis.com 
  billing: billing_test-project 
  concurrent_api_activation: True 
  project: test-project 
type: apis.py
name: service-accounts 
properties: 
  project: test-project 
  service-accounts:  
type: service-accounts.py
action: gcp-types/compute-v1:compute.projects.setUsageExportBucket 
metadata: 
  dependsOn: test-projecttest-project-compute.googleapis.com 
name: set-export-bucket 
properties: 
  bucketName: gs://usage-exports 
  project: test-project 
  reportNamePrefix: usage_gce_

请注意:

  1. 如果您无法使用F-strings由于您的 Python 版本 (< 3.6),您可以使用 str 类的 format() 函数。
  2. 如果你需要这些连字符,比如前面的“名称”(我不太清楚它们应该在输出中的其他位置),你可以创建一个时态字典,其中包含在它们应该存在的键中并应用我提供的 unpack_dict() 函数,传递该时态字典而不是原始资源

关于Python - 将字典和键值列表转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61873581/

相关文章:

python - 如何指定spaCy根据句号识别句子

python - 编译用于 mac OSX 10.8 上的 python 包装器的 C 库

c# - 删除一个词及其后的所有内容

python - 查找列表的最小值并从另一个列表中打印相应的索引

python - Jinja2 忽略未找到对象的 UndefinedErrors

python - 如何在 Django 中进行复杂的包含查询?

Android 对 ListView 的项目使用 NumberFormat

python - Python 中 "string"的逻辑值是多少?

python - 如何填充列表中的值并将其转换为数据帧?

python - 在不使用 itertools 的情况下查找嵌套列表的总和