Python / Pycharm: для l oop выборка строки вместо словаря - PullRequest
0 голосов
/ 08 апреля 2020

Я новичок в python, так что это может показаться очень глупым вопросом, пожалуйста, потерпите меня.

Я использую следующий код: (изображение, если отладка также прилагается)

for connector in la_details['properties']['parameters']['$connections']['value']:
    if connector['connectionName'] in allowed_connectors:
        result = True

Pycharm Debug

Теперь вместо извлечения значения 'dict' из переменной 'connector' он извлекает 'string', из-за чего оператор 'if' выдает ошибку:

string indices must be integers

Может кто-нибудь подсказать, как получить значения 'dict' вместо 'string'? Я пытался Google, но не смог найти ничего, что соответствует этому сценарию, возможно, потому что я использую неправильную терминологию.

РЕДАКТИРОВАТЬ: print (la_details) производит следующий вывод:

{u'name': u'REDACTED',
 u'tags': {},
 u'id': u'/subscriptions/REDACTED/resourceGroups/REDACTED/providers/Microsoft.Logic/workflows/REDACTED',
 u'location': u'REDACTED',
 u'type': u'Microsoft.Logic/workflows',
 u'properties': {u'definition': {u'parameters': {u'$connections': {u'defaultValue': {}, u'type': u'Object'}}, u'triggers': {u'Recurrence': {u'recurrence': {u'frequency': u'Month', u'interval': 1}, u'type': u'Recurrence'}}, u'outputs': {}, u'actions': {u'Send_an_email_(V2)': {u'inputs': {u'body': {u'Body': u'<p>TEST</p>', u'To': u'REDACTED', u'Subject': u'TEST'}, u'path': u'/v2/Mail', u'host': {u'connection': {u'name': u"@parameters('$connections')['office365']['connectionId']"}}, u'method': u'post'}, u'runAfter': {}, u'type': u'ApiConnection'}, u'Get_tables_(V2)': {u'inputs': {u'path': u"/v2/datasets/@{encodeURIComponent(encodeURIComponent('default'))},@{encodeURIComponent(encodeURIComponent('default'))}/tables", u'host': {u'connection': {u'name': u"@parameters('$connections')['sql']['connectionId']"}}, u'method': u'get'}, u'runAfter': {u'Send_an_email_(V2)': [u'Succeeded']}, u'type': u'ApiConnection'}}, u'contentVersion': u'1.0.0.0', u'$schema': u'https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#'}, u'version': u'REDACTED', u'parameters': {u'$connections': {u'value': {u'office365': {u'connectionId': u'/subscriptions/REDACTED/resourceGroups/REDACTED/providers/Microsoft.Web/connections/office365', u'id': u'/subscriptions/REDACTED/providers/Microsoft.Web/locations/eastus/managedApis/office365', u'connectionName': u'office365'}, u'sql': {u'connectionId': u'/subscriptions/REDACTED/resourceGroups/REDACTED/providers/Microsoft.Web/connections/sql', u'id': u'/subscriptions/REDACTED/providers/Microsoft.Web/locations/eastus/managedApis/sql', u'connectionName': u'sql'}}}}, u'integrationServiceEnvironment': {u'type': u'Microsoft.Logic/integrationServiceEnvironments', u'name': u'ise-demo-res', u'id': u'/subscriptions/REDACTED/resourceGroups/REDACTED/providers/Microsoft.Logic/integrationServiceEnvironments/ise-demo-res'}, u'endpointsConfiguration': {u'connector': {u'outgoingIpAddresses': [{u'address': u'40.71.11.80/28'}, {u'address': u'REDACTED'}, {u'address': u'REDACTED'}, {u'address': u'REDACTED'}, {u'address': u'REDACTED'}, {u'address': u'REDACTED'}, {u'address': u'REDACTED'}, {u'address': u'REDACTED'}, {u'address': u'REDACTED'}]}, u'workflow': {u'outgoingIpAddresses': [{u'address': u'REDACTED'}, {u'address': u'REDACTED'}], u'accessEndpointIpAddresses': [{u'address': u'REDACTED'}]}}, u'state': u'Enabled', u'accessEndpoint': u'REDACTED', u'createdTime': u'2020-03-12T14:45:34.6908438Z', u'changedTime': u'2020-04-08T10:35:32.3388762Z', u'provisioningState': u'Succeeded'}}

1 Ответ

0 голосов
/ 08 апреля 2020

In python for ... in ... возвращает либо значение в случае списков, либо ключ в случае словарей (как в вашем примере), ниже приведен правильный способ сделать ваше l oop.

la_details = {
  'properties': {
    'parameters': {
      '$connections': {
        'value': {
          'office365': { 'connectionName': 'office365' },
          'sql': { 'connectionName': 'sql' },
        }
      }
    }
  }
}

allowed_connectors = ['sql']

#for connector in la_details['properties']['parameters']['$connections']['value']:
#  if connector['connectionName'] in allowed_connectors:
#    return True
#  else:
#    return 'False

values = la_details['properties']['parameters']['$connections']['value']

for connector in values:
  if values[connector]['connectionName'] in allowed_connectors:
    print('{0} is allowed'.format(values[connector]['connectionName']))
  else:
    print('{0} is not allowed'.format(values[connector]['connectionName']))
...