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}
No Comments/Pingbacks for this post yet...
Donate to keep this site going!
| 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 | |||