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.

Writing your research paper in Latex using texmaker 3.0.4 (Part 2)

This is the second part of my previous post on the same topic Writing your research paper in Latex using texmaker 3.0.4 : Some useful commands and tips. So here are the new tid-bits:

1. Sort Citations by Reference Number

If you are happen to be using a bib style other than ieeetr and need to sort citations then use the following in your premble –




The latter would format the list as [1–3] while the former gives [1, 2, 3]

2. BibTeX Style Examples

If you are confused about which bibtex style your publisher uses then you can search this style example archive.

3. Aligning on specific character for multiline equations with one equation number

Use the split environment with only one ampersand at the alignment point, which would be the equals sign for your case. So, for instance, your code would be:

   A + B &= C + D \\
   &= E + F  \\
   &= 3

So here the equation will align around the ‘=’ sign. And ‘\\’ splits the equations in separate lines.

4. Remove colon from table and figure name, making bold
The caption package provides a lot of functionality and I would recommend to use it. You get Figure x.x bold with


when you load the package.
Use the caption package with the labelsep=space option to remove colon.


5. How to break a long equation/Group equations under a single equation number

Use split environment provided by amsmath package.

F = \{F_{x} \in  F_{c} &: (|S| > |C|) \\
 &\quad \cap (\text{minPixels}  < |S| < \text{maxPixels}) \\
 &\quad \cap (|S_{\text{conected}}| > |S| - \epsilon) \}

6. Making a wide figure or table in a two-column document

Use the starred version * of the figure or table environment. This will usually flush the figure (or table) to the top of the following page, so there is not much control on placement. For table* and figure*, the only available options are t (top of next page) or p (end of document). b and h have been disabled on purpose, there is probably a strong typographical reason behind it.

Note that the table may appear one the next page instead of the current one. If you really need to control on what page the table is, you may have to move the table definition up in the source code.

Figure* Example:

  \caption{This is a tiger.}

Table* example:

\lipsum[1-10] % To create a random first page
[Location of the table in source code]
    1 & 2 & 3 \\
    4 & 5 & 6 \\
    7 & 8 & 9

7. Labels and Cross-referencing

This is very useful. In LaTeX you can easily reference almost anything that is numbered (sections, figures, formulas), and LaTeX will take care of numbering, updating it whenever necessary. Go to the following link to know how its done.