简体   繁体   English

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

[英]Python - Convert List Of Dictionaries & Key Values To String

Take the following list of dictionaries and key value pairs:获取以下字典和键值对列表:

              [{'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_'}}]}

I need to convert this into the following syntax:我需要将其转换为以下语法:

resources:\n- name: test-project\n properties:\n name: test-project\n parent:\n id:\n type: folder\n资源:\n- 名称: test-project\n 属性:\n 名称: test-project\n 父级:\n id:\n 类型: 文件夹\n

I thought perhaps something like the following would work following my brief Google search:我认为在我简短的 Google 搜索之后,可能会使用以下内容:

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

Unfortunately, that then gives me the error: "TypeError: sequence item 0: expected str instance, dict found"不幸的是,这给了我错误:“TypeError:序列项0:预期的str实例,找到字典”

Any help with this would be greatly appreciated.对此的任何帮助将不胜感激。

(As a side note, Google's only example of the config content being a string is for creating a VM: https://cloud.google.com/deployment-manager/docs/deployments#api ; I notice that the spaces seem to increase with each key value pair, but I'm not entirely sure if that's actually required here or not). (作为旁注,Google 将配置内容作为字符串的唯一示例是用于创建 VM: https://cloud.google.com/deployment-manager/docs/deployments#api ;我注意到空间似乎在增加每个键值对,但我不完全确定这里是否真的需要)。

EDIT: Apologies, I meant to say I need the key value pairs in a similar format to the below, as a string:编辑:抱歉,我的意思是说我需要与以下格式类似的键值对作为字符串:

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"

So, when printed, it looks like this:因此,打印时,它看起来像这样:

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_

Try applying the following recursive function.尝试应用以下递归 function。 This should work for your specific use case:这应该适用于您的特定用例:

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()

output for print(result) output 用于print(result)

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_

Please note:请注意:

  1. If you can't use F-strings due to your Python version (< 3.6), you can use the format() function of the str class.如果由于 Python 版本(< 3.6)而无法使用F 字符串,则可以使用str ZA2F2ED4F8EBC2CBB4C21A29DC40AB61D 的format() function。
  2. If you need those hyphens, like the one prepending "name" (which I'm not clear enough where else they should go in the output), you could create a temporal dictionary with those included in the keys where they are supposed to be, and apply the unpack_dict() function I provided, passing that temporal dictionary instead of the original resources .如果您需要这些连字符,例如前面的“名称”(我不太清楚它们应该在输出中的其他位置 go),您可以创建一个临时字典,其中包含它们应该在的键中包含的那些,并应用我提供的unpack_dict() function,传递那个时间字典而不是原始resources

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM