简体   繁体   中英

Is finding a key in a dictionary takes the same time as finding an item in a list

I have a dictionary with 1,000,000 keys, I want to check if a certain key exists in a dictionary. I could also have 1,000,000 items in a list which would hold all of those keys.

Which is the faster way and why?

For example:

999999 in {x:x for x in range(1000000)}

vs

999999 in [x for x in range(1000000)]

Dictionaries are faster because keys are hashed. See here: https://wiki.python.org/moin/TimeComplexity

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