Dict and set of Python learning

Source: Internet
Author: User

#coding=utf-8# dictdict= {‘bob‘: 40, ‘andy‘: 30}print dict[‘bob‘]# 通过dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value:print dict.get(‘Lisa‘,666)# 要删除一个key,用pop(key)方法,对应的value也会从dict中删除:dict.pop(‘bob‘)print dict‘‘‘ 1.dict内部存放的顺序和key放入的顺序是没有关系的。 2.和list比较,dict有以下几个特点:    2.1.查找和插入的速度极快,不会随着key的增加而增加;    2.2.需要占用大量的内存,内存浪费多。 所以,dict是用空间来换取时间的一种方法。 3.dict的key必须是不可变对象。 ‘‘‘# set# set和dict类似,也是一组key的集合,但不存储value。s = set([1, 2, 3,4,4,6])print ‘s=‘, s# add(key)s.add(‘Greta‘)s.remove(6)print ‘after change:‘,s# 交集、并集s1 = set([1,2,3])s2 = set([1,3,4])print ‘交集‘,s1&s2print ‘并集‘,s1|s2# 不可变对象list = [5,2,3,10,4]list.sort()print ‘after sort:‘, listteacher=‘Andy‘teacher.replace(‘Andy‘,‘Bob‘)print teacher# 总结:set不接受可变元素,所以用turple没问题,但是如果有list就会报错

Python learning dict and set

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.