[Tutor] Creating a dictionary

Steven D'Aprano steve at pearwood.info
Fri May 27 16:34:00 CEST 2011


Válas Péter wrote:
> Hi,
> I think I am new to here, as far as I remember. :-)
> 
> http://docs.python.org/dev/library/stdtypes.html#dict says:
> we can create a dictionary with
> 
>    - dict({'one': 1, 'two': 2})
> 
> What is the adventage of this form to simply writing d = {'one': 1, 'two': 2}?
> Is there any difference?

dict() is a function (technically, a type) that creates new dictionaries 
from whatever argument you pass to it. { ... } is syntax for creating 
literal dictionaries. Think of this as similar to the difference between 
a mathematical expression:

x = 2*9-1

and a number literal:

x = 17


HOWEVER, in the above example with dict(), the form shown is redundant. 
dict({'one': 1, 'two': 2}) does these four steps:

(a) Python creates a dictionary using the "dict literal" syntax
     {'one': 1, 'two': 2}
(b) That dictionary is then passed to the dict() function
(c) The dict() function makes a copy of that dictionary and returns it
(d) Python's garbage collector deletes the original dictionary.

Never put a lone dict literal {...} inside a call to dict(), that's just 
a waste of time. Just use the literal on its own.

dict() *can* be very useful, just not in the example shown. You can use 
it to make copies of other dicts:


first_dict = {'one': 1, 'two': 2}
second_dict = dict(first_dict)


That's not very interesting, as you can easily make a copy with 
first_dict.copy() instead. But it gets more interesting if you want to 
add new items to the dictionary:


third_dict = dict(first_dict, three=3, four=4)


You can even leave out the original dict:


fourth_dict = dict(a=1, b=2, c=3)


or instead use a list of (key, value) pairs:


items = [('a', 1), ('b', 2), ('c', 3)]
fifth_dict = dict(items, d=4)



-- 
Steven



More information about the Tutor mailing list