Some frequently used python snippets

Jotting down here some python snippets that I seem to frequently use. So here goes –

1. creating dictionary of dictionaries

In [12]: x = {1:'a', 2:'b'}
In [13]: x
Out[13]: {1: 'a', 2: 'b'}
In [14]: x['c'] = {}
In [15]: x
Out[15]: {1: 'a', 2: 'b', 'c': {}}
In [16]: x['c']['name'] = 'abc'
In [17]: x
Out[17]: {1: 'a', 2: 'b', 'c': {'name': 'abc'}}

2. return multiple values from a function

def f(in_str):
    out_str = in_str.upper()
    return True, out_str # Creates tuple automatically

succeeded, b = f("a") # Automatic tuple unpacking

3. Check if a given key already exists in a dictionary

in is the intended way to test for the existence of a key in a dict.

d = dict()

for i in xrange(100):
    key = i % 10
    if key in d:
        d[key] += 1
        d[key] = 1

4. How do I check if a file exists

if you don’t want to touch the file if it doesn’t exist

import os.path

5. How to modify list entries during for loop

It’s considered poor form. Use a list comprehension instead, with slice assignment if you need to retain existing references to the list.

a = [1, 3, 5]
b = a
a[:] = [x + 2 for x in a]
print b

remember that even if you modify the list, the loop counter doesn’t change its value.

6. read json file

There’s no need to first read the file, then use loads. You can just use load directly.

output_json = json.load(open('/tmp/output.json'))

7. dump a dictionary to json file

d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)

8. add new key-value pair to dictionary

dict.update({'item3': 3})

9 Add item or list of items to a list

list = []
x = 1
list += another list

10. Check if a variable exists

To check the existence of a local variable:

if 'myVar' in locals():
  # myVar exists.

To check the existence of a global variable:

if 'myVar' in globals():
  # myVar exists.

To check if an object has an attribute:

if hasattr(obj, 'attr_name'):
  # obj.attr_name exists.

Another method,

except NameError:
    myVar = None
# Now you're free to use myVar without Python complaining.

11. Change the key value in dictionary

dict[new_key] = dict.pop(old_key)

Note that, this will raise KeyError if dict[old_key] is undefined.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s