A preliminary understanding of the dict of Python practice (I.)

Source: Internet
Author: User
Tags iterable

Dictionary full Name (dictionaries)
字典为非线性结构类似Dict称为k-v对、全名为:key - value键值对的数据的集合dict是可变的、无序的、key不重复(去重)*key必须可以hash*set可称为dict的简化版dict是一个个kv对,其中k一定不相同,keys可以当set用、如果value可hash,那么items可以当set用
Dictionary dict definition Initialization
 d = dict() 或者d = {} dict(**kwarge)使用name = value对构造字典,不过可迭代对象的元素必须是一个二元结构 dict(iterable,**kwary)可用迭代对象和name = value对构造字典,不过可迭代对象的元素必须是一个二元结构 d = dict(((1,‘a‘),(2,‘b‘)))或者 d = dict(([1,‘a‘],[2,‘b‘]))(二元组) dict(mapping,**kwarg)使用一个字典构建另一个字典*含有引用类型,注意结果 d = {‘a’:10,‘b‘:20,‘c‘:None,‘d‘:[1,2,3]} #常用构建字典方式 类方法dict.fromkeys(iterable,value)                d = dict.fromkeys(range(5))                d = dict.fromkeys(range(5),0) 当iterable的key与kwary的值相同时,后面的value会覆盖前面的value
Access to dictionary elements
*d[key]    返回key对应的value    key不存在抛出KeyError异常*get(key[,default])    返回key对应的value    key不存在时返回缺省值,如果没有设置缺省值就返回Nonesetdefault(key[,default]    返回key对应的值value    key不存在,添加kv对,value设置为default,并返回default,如果default没有设置,缺省为None
Dictionary Additions and modifications
d[key] = value     将key对应的值修改为value     key不存在添加新的kv对update([other]) - >None    使用另一个字典的kv对更新本字典、    key不存在,就添加    key存在,覆盖已经存在的key对应的值    就地修改    *当key为数字,默认无法添加。需使用二元组方式,或字典方式添加
Dictionary Delete
pop(key[,defaulf])        key存在,移除它,并返回它的value        key不存在,返回给你的default        default未设置,key不存在则抛出keyError异常popitem()        移除并返回一个任意的键值对        字典empty,抛出KeyError异常clear()        清空字典del语句        删除非value本事,而是value的引用计数。当引用计数归零时,内存会自动回收。

A preliminary understanding of the dict of Python practice (I.)

Related Article

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.