Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

differences between "d = dict()" and "d = {}"

$ python2.7 -m timeit 'd={}' 10000000 loops, best of 3: 0.0331 usec per loop $ python2.7 -m timeit 'd=dict()' 1000000 loops, best of 3: 0.19 usec per loop 

Why use one over the other?

like image 449
tshepang Avatar asked Apr 30 '10 13:04

tshepang


People also ask

Is dict () and {} the same?

The setup is simple: the two different dictionaries - with dict() and {} - are set up with the same number of elements (x-axis). For the test, each possible combination for an update is run.

Is {} a set or dict?

Well, a set is like a dict with keys but no values, and they're both implemented using a hash table. But yes, it's a little annoying that the {} notation denotes an empty dict rather than an empty set , but that's a historical artifact.

Is {} a dictionary in Python?

What is a Python dictionary? A dictionary is an unordered and mutable Python container that stores mappings of unique keys to values. Dictionaries are written with curly brackets ({}), including key-value pairs separated by commas (,).

Is {} in Python a dict or set?

It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {} .


2 Answers

I'm one of those who prefers words to punctuation -- it's one of the reasons I've picked Python over Perl, for example. "Life is better without braces" (an old Python motto which went on a T-shirt with a cartoon of a smiling teenager;-), after all (originally intended to refer to braces vs indentation for grouping, of course, but, hey, braces are braces!-).

"Paying" some nanoseconds (for the purpose of using a clear, readable short word instead of braces, brackets and whatnots) is generally affordable (it's mostly the cost of lookups into the built-ins' namespace, a price you pay every time you use a built-in type or function, and you can mildly optimize it back by hoisting some lookups out of loops).

So, I'm generally the one who likes to write dict() for {}, list(L) in lieu of L[:] as well as list() for [], tuple() for (), and so on -- just a general style preference for pronounceable code. When I work on an existing codebase that uses a different style, or when my teammates in a new project have strong preferences the other way, I can accept that, of course (not without attempting a little evangelizing in the case of the teammates, though;-).

like image 127
Alex Martelli Avatar answered Sep 29 '22 02:09

Alex Martelli


d=dict() requires a lookup in locals() then globals() then __builtins__, d={} doesn't

like image 23
John La Rooy Avatar answered Sep 29 '22 01:09

John La Rooy