OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Strange Default Behavior For Python Dict Get Method

  • Thread starter Thread starter Bigbob556677
  • Start date Start date
B

Bigbob556677

Guest
We recieve API requests from two versions of embedded systems as follows.

Code:
data = {"sender": "555-555-5555"} #new version

data = {"from": "555-555-5555"} #old version

To support backwards compatibility with older systems I wrote the code.

data.get("sender", data["from"]))

Question

When I pass the dict containing the key "sender" to it, I would expect it not to even evaluate the default value from the key "from", but instead it throws a KeyError for the key 'from'.

I know how to fix the issue, but why would python be evaluating the default when the key is present?

Note the following code.

Code:
{"sender": "111-111-1111"}.get("sender", {"from": "222-222-2222"}['from'])

This returns 111-111-1111 but if i change the key in the default, it fails with a KeyError
<p>We recieve API requests from two versions of embedded systems as follows.</p>
<pre><code>data = {"sender": "555-555-5555"} #new version

data = {"from": "555-555-5555"} #old version
</code></pre>
<p>To support backwards compatibility with older systems I wrote the code.</p>
<p><code>data.get("sender", data["from"]))</code></p>
<p><strong>Question</strong></p>
<p>When I pass the dict containing the key "sender" to it, I would expect it not to even evaluate the default value from the key <code>"from"</code>, but instead it throws a KeyError for the key 'from'.</p>
<p>I know how to fix the issue, but why would python be evaluating the default when the key is present?</p>
<p>Note the following code.</p>
<pre><code>{"sender": "111-111-1111"}.get("sender", {"from": "222-222-2222"}['from'])
</code></pre>
<p>This returns 111-111-1111 but if i change the key in the default, it fails with a KeyError</p>
 

Latest posts

Online statistics

Members online
0
Guests online
3
Total visitors
3
Top