Python Learning 6-built-in data structure 4-dictionaries

Source: Internet
Author: User

A dictionary is a key-value structure
1. Definition
D = {}
D = dict ()
D = {' A ': 1, ' B ': 2}
D = dict ([' A ', 1],[' B ', 2]) #可迭代对象的元素必须是二元组, the No. 0 element of the two-tuple is key, and the 1th element is a Vlaue
D = Dict.fromkeys (range (5)) #传人可迭代对象的key with a value of none
D = Dict.fromkeys (range (5), ' abc ') #传人可迭代对象的key with a value of ABC
2. Increase
D[' a '] = 1 #可以直接使用key作为下标, does not exist will increase.
D.update ([' C ', 3), (' d ', 0)])
D.update (dictionary) #通常用于合并字典
3. Modification
d[' key '] = value #当key存在则修改
4. Delete
D.pop (key[, ' Default ')) #删除并返回该key的value, there is no key error. Returns the default value when there is a default value when key does not exist
D.popitem () #随机删除并返回一个二元组, empty dictionary key error
D.clear () #清空字典
5. Visit
D[key] #通过key访问value, there is no key error
D.get (key[, ' Default ') #不存在返回none, default value is returned when there is a default value
D.setdefault (key[, ' Default ') #key存在返回value, the default value for adding the Key,value does not exist.
D.keys () #返回字典的key
D.values () #返回字典的value
D.items () #返回字典的key和vaue
D.keys () d.values () D.items () is the return list in P2, which copies a copy of the memory, P3 in the generator, does not replicate within the P2 can be used D.iteritems ()
6. Dictionary Restrictions
The key of the dictionary cannot be duplicated, and can be hash, unordered
7. Default Dictionary
From collections Import Defaultdict
D1 = defaultdict (list) #default初始化时, need to pass in a function, this function is also called the factory function, when we access the key by subscript does not exist, Defaultdict will call the function to generate an object as the value of this key.
8. Ordered dictionary
D = ordereddict () #按插入顺序

Python Learning 6-built-in data structure 4-dictionaries

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.