Conditional access to items in Python

Question:

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.

Asked By: someone

||

Answers:

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', '')
Answered By: blhsing
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.