<p>I want to write some tests for Kubernetes with python. This is a sample of my deployment file in Kubernetes:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: test-service
  namespace: test
  creationTimestamp: '2022-12-08T18:18:49Z'
  labels:
    app: test-service
    team: teamA
.
.
</code></pre>
<p>what I want to do is get access to the items inside the deployment file:</p>
<pre class="lang-py prettyprint-override"><code>some codes here....
result = set()
some codes here.....
    with open(deoloyment_file, &quot;r&quot;) as stream:
        for data in yaml.safe_load_all(stream.read().replace('\t', '  ')):
            if data and data['kind'] == 'Deployment':
                result.add(f&quot;{data['metadata']['namespace']}:{data['metadata']['name']}:{data['metadata']['labels']['team']}&quot;)
</code></pre>
<p>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.</p>

<p>You can specify a default value for the <code>dict.get</code> method to make it fall back to the value when a given key does not exist.</p>
<p>Assuming you want an empty string when either <code>labels</code> or <code>team</code> doesn't exist, you can change:</p>
<pre><code>data['metadata']['labels']['team']
</code></pre>
<p>to:</p>
<pre><code>data['metadata'].get('labels', {}).get('team', '')
</code></pre>
