Python dictionary ordered unordered and search efficiency, hash table

Source: Internet
Author: User

When I first learned python, I thought that the dictionary was unordered, and by multiple insertions, such as Di = {}, multiple di[' TestKey ']= ' testvalue ' test to prove unordered.
Later came into contact with the dictionary search efficiency this thing, checked, the original dictionary in Python is in the order of the hash table to do some testing, such as Di = {1:1,3:3,2:2,4:4,5:5}, regardless of how the order of key-value pairs, print di will always {1:1, 2:2, 3:3, 4:4, 5:5}. So it seems that when inserting di[' key ']= ' value ', this set of key pairs sometimes does not go to the last position.
So it can also be said that the dictionary is orderly.
Of course, the concept of order and disorder here depends on where you are easy to understand, from the data structure it is the order of the hash table, but from the display layer it does not from left to right by the assignment of the added.

In addition, the value of the Python dictionary, regardless of length, its time/space complexity is O (1).

Leetcode list Two values add equal to a number, return two values corresponding to the title of the index, if you want to use a single-layer loop to achieve, just use the hash table.

https://leetcode.com/problems/two-sum/

Implementation code:

Class solution (Object):
def twosum (self, Nums, target):
"""
: Type Nums:list[int]
: Type Target:int
: Rtype:list[int]
"""
dict={}
For i,x in Enumerate (nums):
If Dict.get (target-x,none) = = None:
Dict[nums[i]] = i
Else
Return (Dict[target-x],i)
Faster than a double-decker cycle speed.

Python dictionary ordered unordered and search efficiency, hash table

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.