Archive for the ‘Python’ Category

List Comprehension

Posted: February 21, 2012 in Devops, Featured, Python
Tags: ,

Why is it better to use list comprehension instead of map + lambda?

(more…)

Advertisements

I’ve started using the string formatting dictionaries and never looked back.

As the ‘%’ operator is deprecated in python 3, I’ve added the future version too.

Python 3.2 (r32:88445, Feb 21 2011, 21:11:06) 
[GCC 4.6.0 20110212 (Red Hat 4.6.0-0.7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> fdict = {'name': 'AJ'}
>>> print('%(name)s is my friend' % fdict)
AJ is my friend
>>> '{name} is my friend'.format(**fdict)
AJ is my friend

I recently had the problem that I needed to pass a set of generated keyword arguments to a function in python. I took a lot of digging, but I’ve now started using it a lot.

Lets take a simple function that takes 5 keywork arguments (kwards):

def function_with_five_kwargs(first='1st', second='2nd', third='3rd',
fourth='4th', fifth='5th'):
    return '%s, %s, %s, %s, %s' % (first,       second, third, fourth, fifth)

If you run this without kwargs, your output is:

1st, 2nd, 3rd, 4th, 5th

If you now want to change all those args, use a dictionary:

my_dict = {'first': 'first',
               'second': 'second',
               'third': 'third',
               'fourth': 'fourth',
               'fifth': 'fifth'}

print function_with_five_kwargs(**my_dict)

Now your output will be:

first, second, third, fourth, fifth