Home > OS >  Conditional access to items in Python
Conditional access to items in Python

Time:12-09

I want to write some tests for Kubernetes with python. This is a sample of my deployment file in Kubernetes:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: test-service
  namespace: test
  creationTimestamp: '2022-12-08T18:18:49Z'
  labels:
    app: test-service
    team: teamA
.
.

what I want to do is get access to the items inside the deployment file:

some codes here....
result = set()
some codes here.....
    with open(deoloyment_file, "r") as stream:
        for data in yaml.safe_load_all(stream.read().replace('\t', '  ')):
            if data and data['kind'] == 'Deployment':
                result.add(f"{data['metadata']['namespace']}:{data['metadata']['name']}:{data['metadata']['labels']['team']}")

This throws an exception because in some deployments files there are no labels or team. I'm wondering how can I conditionally access items with Python.

CodePudding user response:

You can specify a default value for the dict.get method to make it fall back to the value when a given key does not exist.

Assuming you want an empty string when either labels or team doesn't exist, you can change:

data['metadata']['labels']['team']

to:

data['metadata'].get('labels', {}).get('team', '')
  • Related