4 Comments

Thanks Meng!

Expand full comment

Question 1: Option A is more efficient because Option B is duplicative (using the dict function on a dictionary

Question 2: Pretty sure you can’t have lists as keys, it’s only supposed to be a single value like a string or number but let me know if there’s a better explanation for why

Expand full comment
author

Question 2:

Using a list as a key is not allowed here because a list is a mutable data structure, while keys in a dictionary must be immutable. The reason is straightforward: keys must be unique. If keys could change, there might be duplicate keys, which would violate the definition of a dictionary. However, if we replace the list with a tuple, which is immutable, it is allowed.

Expand full comment
author
Jul 9·edited Jul 9Author

Question 1:

The first method is faster because it doesn't require calling related functions, and {} should be a keyword that directly invokes the underlying C code.

A = {}: Creates a dictionary and assigns it to A.

A = dict({}): Creates a dictionary as a parameter for the dict function, calls the dict function, and assigns the return value to A.

The latter is slower because the steps it executes are a subset of the steps in the former.

import timeit

print(timeit.timeit(stmt="d = {'name': 'jason', 'age': 2}", number=100000))

print(

timeit.timeit(

stmt="d = dict({'name': 'jason', 'age': 20, 'gender': 'male'})",

number=100000))

d = {

'name': 'jason',

'education': ['Tsinghua University', 'Stanford University']

}

0.012273817000000006

0.04732211700000001

The latter is four times slower than the former.

Expand full comment