简体   繁体   中英

Python dict.update vs initializing completely in starting

I have to define a dict with about 50,000 keys and value -1. Each key is updated based on if condition. Also not all keys will be updated.

One way to do this is to initialize complete dict and then use for loop to update values. Another way can be to initialize an empty dict and then update it only for values updated.

My question is whether it takes same amount of time/computation to initialize a very large dict or update it on the fly. Is update too much expensive ?

You could use a defaultdict which in the case of a missing key, returns a default value.
Note: defaultdict needs a callable for initialization, that's why I use this lambda function,
which simply returns the initialization value.

from collections import defaultdict
def_dict = defaultdict(lambda:-1)
def_dict[500] = 2

print(def_dict[0])
print(def_dict[500])

So instead of iterating all 50.000 keys to initialize them, you could just iterate the desired subset, without worrying about the rest.

Output:

-1
2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM