Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8972051
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T18:07:08+00:00 2026-06-15T18:07:08+00:00

Is there a way to do a ternary operation on a dict where the

  • 0

Is there a way to do a ternary operation on a dict where the test is has_key() without hitting the key error? i.e.

variable = dict["the_key"] if dict.has_key("the_key") else "something"

(this hits the key error obviously)

failing that, what’s the most pythonic way to assign a bunch of variables values based on a dict that may or may not have the keys in question? Repeating:

if dict.has_key('key'):
    value = dict['key']
else:
    value = "value"

ad nauseum seems to be very inelegant.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T18:07:09+00:00Added an answer on June 15, 2026 at 6:07 pm

    Jochen Ritzel’s answer is the right way to do this 99.9999% of the time:

    variable = d.get("the key", "something")
    

    As he notes, it doesn’t allow you to short-circuit the evaluation of the default value. You usually don’t care. It the default value is "something", you certainly don’t. It only matters if the default is either dangerous, or very expensive, to generate.

    Only in that case, you can and should use your idea. Except that you want in instead of has_key (because it’s more readable, and faster, and not deprecated):

    variable = d["the key"] if "the key" in d else expensiveComputation()
    

    However, it’s probably worth using an if statement instead of a ternary expression, because the fact that you’re avoiding the expensiveComputation is important, and you want it to be more visible:

    if "the_key" in d:
        variable = d["the key"]
    else:
        variable = expensiveComputation()
    

    If you expect the default case to be rare, this is better:

    try:
        variable = d["the key"]
    except KeyError:
        variable = expensiveComputation()
    

    If for some reason you need to avoid looking the key up twice, and you also can’t deal with exceptions, and you need to short-circuit the default, all at once:

    sentinel = object()
    variable = d.get(sentinel)
    if variable == sentinel:
        variable = expensiveComputation()
    

    And yes, you could wrap that all up in a function so it’s a one-liner, but you almost certainly don’t want to hide the fact that you’re doing three rare things all at once.

    Or, of course, you could just make do this:

    d = collections.defaultdict(expensiveComputation)
    

    Then, it’s just:

    variable = d["the key"]
    

    This has the side-effect of setting d["the key"] to expensiveComputation() before returning it to you, so a later call to d["the key"] will return the same value. If that sounds appropriate, this is the best answer; if you’re never going to use the same key twice, or these things are huge and wasteful to keep around, etc., this is a bad idea.

    Or, alternatively, you can override the dict.__missing__ method instead of using defaultdict:

    class MyDict(dict):
        def __missing__(self, key):
            return expensiveComputation()
    

    Then, again, it’s just:

    variable = d["the key"]
    

    This one is appropriate when you want to generate the value separately each time, and not keep it around for later.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there a way to do ternary operators in Velocity? This is what I'd
Is there way to automatically maximize the output window on hitting build and then
Is there way to set @include mixin(); to variable? I tried this @mixin bg-gradient($fallback,
Is there a way to have the ternary operator do the same as this?:
Is there way to get file from windows xp command prompt? I tried to
Is there way to copy a file into Plone with WebDAV and have Plone
is there way how to get name ov event from Lambda expression like with
Is there way to better identify design pattern in source codes, esp. if you
Is there way to mute an audio stream or at least control the volume?
Is there way that I can read the file from remote server using fopen

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.