Post details: dictionary fun

10/25/06

Permalink 07:29:25 am, Categories: Python, 175 words   English (US)

dictionary fun

Learned some new things about Python dictionaries. Let's say you wanted to create a dictionary with keys given in a list, and a default value for all of them, say None.

>>> somelist=['foo', 'bar', 'baz']
>>> {}.fromkeys(somelist)
{'baz': None, 'foo': None, 'bar': None}

Or some other value, like True:

>>> {}.fromkeys(somelist, True)
{'baz': True, 'foo': True, 'bar': True}

An uglier way to do this is with a list comprehension:

>>> dict([(x, True) for x in somelist])
{'baz': True, 'foo': True, 'bar': True}

Now you can easily see a way to uniq-ize a list:

>>> somelist=['foo', 'bar', 'foo']
>>> {}.fromkeys(somelist).keys()
['foo', 'bar']

But really, there is an even better way to uniq-ize a list in 2.4:

>>> list(set(somelist))
['foo', 'bar']

On another note, let's say I wanted to loop through the keys of a dict in sorted order in Python 2.4:

>>> somelist=['foo', 'bar', 'baz']
>>> somedict={}.fromkeys(somelist)
>>> for key in sorted(somedict):
...   print key
... 
bar
baz
foo

Or, did you know you can create a dict with x=y arguments?

>>> dict(x=1,y=2)
{'y': 2, 'x': 1}

Comments, Pingbacks:

No Comments/Pingbacks for this post yet...

Leave a comment:

 
 

This is a captcha-picture. It is used to prevent mass-access by robots. (see: www.captcha.net)

You must read and type the 5 chars within 0..9 and A..F, and submit the form.

  

Oh no, I cannot read this. Please, generate a

Viraj's Weblog

Donate to keep this site going!

Amount USD $

June 2011
Mon Tue Wed Thu Fri Sat Sun
<<  <   >  >>
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30      

Search

Categories


Misc

Syndicate this blog XML

What is RSS?

powered by
b2evolution