Wednesday, November 23, 2011

Sort a dictionary of dictionaries in Python

Sounds like a big challenge? not at all!

Problem description:
Suppose you have a dictionary of dictionaries. Every key has a dictionary assigned to it, for example:
mydict = {'hello':dict(key1='val10', key2='val20', key3='val30'),
              'world':dict(key1='val11', key2='val21', key3='val31'),
              'howru':dict(key1='val12', key2='val22', key3='val32')}

and your goal is to get a list of mydict "inner" dictionaries, ordered by key2.

A solution for example:
from operator import itemgetter
mydict_values = mydict.values()
mydict_values.sort(key=itemgetter("key2"))

Explained:
mylist.values() gets the list of values from mydict, which is the "inner" dictionaries.
I'm using sort to sort the list of dictionaries, by key, which is looking for item named key2 as the key.

That's all for this time :-)

Tuesday, November 15, 2011

Temporary disposable email address using Gmail

This is very useful for testing registration processes, where you need to register with a new email address every time.
Suppose you have a gmail address:
name@gmail.com .
You can send emails to:
name+2@gmail.com, name+cnn@gmail.com .
The rule is that you can add any alphanumeric characters after the ‘+’ sign.
All emails would be sent to your name@gmail.com account.

Is nice :-)