简体   繁体   中英

how to repeat / expand expressions in python

What is the most pythonic way to repeat an expression in Python.

Context : A function is getting passed a dictionary (with possibly 20 elements) and I need to extract and use values from this dictionary if they exist . Something like this :

x = dict_name['key1'] if dict_name['key1'] else ''

Now, instead of writing this logic 20 times for all 20 different keys, I would like to define this expression at one place and then use it repeatedly. It will be easier to maintain in future. In "C/C++" programming languages, it makes a good case of #define or inline functions. What would be Pythonic way to do this in Python?

As you would have guessed, I am novice in Python. So I appreciate your help on this or pointers to constructs for this in Python.

Whether there is an "equivalent" to inline in Python depends on who you ask, and what you check.

For no equivalent, eg: https://stackoverflow.com/a/6442497/2707864

For equivalent, eg: https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch07s06.html

From a practical point of view, lambda would do the trick ( dict.get replaces your ternary conditional operator)

dict_get = lambda key : dict_name.get(key, '')

Or you can always define a one-line function.

def dict_get( key ) : dict_name.get( key, '' )

Pythonicity is quite often (always?) subjective.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM