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 7929017
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T19:55:54+00:00 2026-06-03T19:55:54+00:00

I am currently blank on how to do this in an effective way.I thought

  • 0

I am currently blank on how to do this in an effective way.I thought about using objects but I don’t see how they could help in this case. Any ideas?

from random import choice
from copy import deepcopy


def main():

    def rand_int():
        return choice(['yes', 'no'])

    # any nesting, functions possible
    spec = {
        'answer': rand_int,
        'next': {'answer': rand_int},
        'the_answer': 42
    }

    #### looking for elegant (automatic) way to do this
    result = deepcopy(spec)
    result['answer'] = result['answer']()
    result['next']['answer'] = result['next']['answer']()
    #### until here

    # result2 = ...

    print 'result: %s' % result


if __name__ == '__main__':
    main()

please do not tell me to use xsd!

  • 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-03T19:55:56+00:00Added an answer on June 3, 2026 at 7:55 pm

    You can do this with one line in a dictionary comprehension:

    {key: function() for key, function in mydictionary.items()}
    

    Of course, this will throw errors when a value isn’t a function, so if that is a possibility, we can simply add a check with the callable() builtin:

    {key: (function() if callable(function) else function) for key, function in mydictionary.items()}
    

    We then need to deal with the fact that your answer needs to be recursive, this makes it a little more complex, but not too hard to fix:

    def call_all_callables_in_dict(mapping):
        if hasattr(mapping, "items"):
            return {key: call_all_callables_in_dict(value) for key, value in mapping.items()}
        elif callable(mapping):
            return mapping()
        else:
            return mapping
    

    Note that if you have objects with an items attribute or method you wish to store in a dict this function will be run on, this could cause problems. I would recommend changing the name of that attribute or method, or replacing the check with isinstance(dict).

    I would also like to note that for misleading function names rand_int that returns a string of 'yes' or 'no' is probably about as bad as it gets. Generally you want True/False in those situations as well.

    As noted in the comments, pre-Python 2.7, you may not have dictionary comprehensions. To get around this, dict() will take a generator of tuples, so you can replace a dict comprehension like so:

    {x: y for x, y in something.items()}
    

    With:

    dict((x, y) for x, y in something.items())
    

    So, in full:

    from random import choice
    
    def rand_int():
            return choice(['yes', 'no'])
    
    spec = {
        'answer': rand_int,
        'next': {'answer': rand_int},
        'the_answer': 42
    }
    
    def call_all_callables_in_dict(mapping):
        if hasattr(mapping, "items"):
            return {key: call_all_callables_in_dict(value) for key, value in mapping.items()}
        elif callable(mapping):
            return mapping()
        else:
            return mapping
    
    print(call_all_callables_in_dict(spec))
    

    Gives us:

    {'answer': 'no', 'the_answer': 42, 'next': {'answer': 'yes'}}
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i'm currently using this regex /^([0-9\(\)\/\+ \-]*)$/, which is fine,but the problem is i
ax.plot_date((dates, dates), (highs, lows), '-') I'm currently using this command to plot financial highs
I've currently got this in my view file: <%= <em>(#{package.to_company})</em> unless package.to_company.blank? %> Is
I'm currently trying to DRY up this initial verbose code: def planting_dates_not_nil? !plant_out_week_min.blank? ||
Unsure how to get this string to work correctly. Keeps making my page blank.
Currently, the following code shows a blank line if Address2 (which comes from the
Currently I am using HTML files for parts of my user interface. I display
currently, I`m implementing a map App with Mono4Droid and there I`m using a WebView
Currently I have 2 ways of displaying images in a cell, which way will
I'm new to Java and currently involve in a project, this problem confuses me

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.