[Tutor] Creating a dictionary
spawgi at gmail.com
spawgi at gmail.com
Fri May 27 16:31:24 CEST 2011
I think the way - d = dict({'one': 1, 'two': 2}) can be used to created
dictionary using list comprehension.
e.g.
>>> d = dict((i,i**2) for i in range(10))
>>> d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
I do not think the second approach can be used in this fashion.
>From python documentation -
http://docs.python.org/tutorial/datastructures.html
The dict() constructor builds dictionaries directly from lists of key-value
pairs stored as tuples. When the pairs form a pattern, list comprehensions
can compactly specify the key-value list.
I am not an expert. So may be someone can explain it better.
Regards
SWP
2011/5/27 Válas Péter <sulinet at postafiok.hu>
> Sorry, I am afraid, I was not clear enough. So what is the difference
> between
> d = dict({'one': 1, 'two': 2})
> and
> d = {'one': 1, 'two': 2}
> ?
>
--
http://spawgi.wordpress.com
We can do it and do it better.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110527/cf570eb9/attachment.html>
More information about the Tutor
mailing list