《零基础入门学习Python》(25)--字典:当索引不好用时(1)

前言

接下来讲讲字典的使用方式。

知识点

字典属于映射类型。

列表,元祖,字符串等属于序列类型

  • 创建及访问字典

 

>>> brand = ['abc','abcd','abcde','abcdef']
>>> solgan =  ['singe','range','reverse','pop']
>>> print('xxxx: ',solgan[brand.index('abcd')])
xxxx:  range
#下面是字典的创建,上面是用函数模拟
>>> dict1 = {'abc':'singe','abcd':'range','abcde':'reverse','abcdef':'pop'}
>>> print(dict1['abc'])
singe
>>> dict2={1:'one',2:'two',3:'three'}
>>> dict2[3]
'three'
  • 创建一个空字典
#创建一个空字典:

>>> dict1 = {}
>>> dict1
{}
#或者
>>> dict3 = dict()
>>> dict3
{}
  • 创建字典的一些其他方法
  • dict(mapping)从映射对象(key,value)中初始化的新字典,例如:

>>> dict4 = dict((('F',70),('i',105),('s',115),('h',104),('C',67)))
>>> dict4
{'F': 70, 'i': 105, 's': 115, 'h': 104, 'C': 67}
# mapping可以是列表,也可以是元祖
>>> dict1 = dict((['F',70],['i',105],['s',115],['h',104],['C',67]))  
>>> dict1        
{'F': 70, 'i': 105, 's': 115, 'h': 104, 'C': 67}
  • dict(**kwargs)用关键字参数列表中的name = value对初始化的新字典。 例如:
>>> dict4=dict(abc='python',abcd='c++')
>>> dict4
{'abc': 'python', 'abcd': 'c++'}
  • 直接给字典的key赋值和添加新的元素:

>>> dict4['abc']='C#'
>>> dict4
{'abc': 'C#', 'abcd': 'c++'}
>>> dict4['abcde']='C primer plus'
>>> dict4
{'abc': 'C#', 'abcd': 'c++', 'abcde': 'C primer plus'}
>>> 

课后习题

测试题

  • 尝试一下将数据('F':30,'C':67,'h':104,'i':105,'s':115)创建为一个字典并访问键’C’对应值

>>> MyDict = dict((('F', 70), ('i',105), ('s',115), ('h',104), ('C',67)))
>>> MyDict_2 = {'F':70, 'i':105, 's':115, 'h':104, 'C':67}
>>> type(MyDict)
<class 'dict'>
>>> type(MyDict_2)
<class 'dict'>
>>> MyDict['C']
67
  • 用方括号[]括起来的数据我们叫列表,那么使用大括号{}括起来的数据我们就叫字典,对吗?
>>> a = {1, 2, 3, 4, 5}
>>> type(a)
<class 'set'>

不难发现,虽然我们用大括号{}把一些数据括起来了,但由于没有反映出这些数据有映射的关系,所以创建出来的不是字典,而是叫set的东西

  • 你如何理解有些字典做得到,但“万能的”列表却难以实现?
#举个例子
>>> brand = ['李宁', '耐克', '阿迪达斯', '鱼C工作室']
>>> slogan = ['一切皆有可能', 'Just do it', 'Impossible is nothing', '让编程改变世界']
>>> print('鱼C工作室的口号是:', slogan[brand.index('鱼C工作室')])
鱼C工作室的口号是: 让编程改变世界

列表brand,slogan的索引和相对的值是没有任何关系的,我们可以看出唯一有联系的就是两
个列表间,索引号相同的元素是有关系的,所以这里我们通过brand.index('鱼C工作室')这样的
语句,间接的实现通过品牌查找对应的口号的功能。

这确实是一种可实现方法,但用起来,多少有些别扭,效率还不高。况且Python是以简洁为主,
这样子的实现肯定是不能让人满意的,我们需要有字典这种映射类型的出现:

>>> dict1 = {'李宁':'一切皆有可能', '耐克':'Just do it', '阿迪达斯':'Impossible is nothing', '鱼C工作室':'让编程改变世界'}
>>> print('鱼C工作室的口号是:', dict1['鱼C工作室'])
鱼C工作室的口号是: 让编程改变世界
  • 下边这些代码,他们都在执行一样的操作吗?你看得出差别吗
>>> a = dict(one=1, two=2, three=3)
>>> a        
{'one': 1, 'two': 2, 'three': 3}

>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> b    
{'one': 1, 'two': 2, 'three': 3}

>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> c        
{'one': 1, 'two': 2, 'three': 3}

>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> d
{'two': 2, 'one': 1, 'three': 3}

>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> e
{'three': 3, 'one': 1, 'two': 2}
  • 如图,你可以推测出打了马赛克部分的代码吗? 

#利用字符串的分割方法。
data = '1000,小甲鱼,男'
MyDict = {}
(MyDict['id'],MyDict['name'],MyDict['sex']) = data.split(',')
print("ID:    " + MyDict['id'])
print("Name:  " + MyDict['name'])
print("Sex:   " + MyDict['sex'])
ID:    1000
Name:  小甲鱼
Sex:   男

动动手

  • 尝试利用字典特性编写一个通讯录程序吧,功能如图:

#这个程序其还可以复杂一点就是每个if后面都加一个判断是否输入正确
#这里个字典赋值的方法就是前面讲过的——直接给字典的key赋值和添加新的元素
print('---欢迎进入通讯录程序---')
print('---1.:查询联系人资料---')
print('---2.:插入新的联系人---')
print('---3.:删除已有联系人---')
print('---4.:退出通讯录程序---')

txl=dict()


while True:
    
    temp = input('根据提示,请输入你想做的事情!!!!!:')
    while not temp.isdigit():
        print('请重新输入::::')
        temp = input('根据提示,请输入你想做的事情!!!!!:')
        
    instr=int(temp)
    if instr == 1:
        name = input('请输入联系人姓名')
        if name in txl:
            print(name + ':' + txl[name])
        else:
            print('您输入的姓名不在通讯录中!')
    elif instr == 2:
        name = input('请你想插入的联系人姓名: ')
        if name in txl:
            print('您输入的姓名已存在 -->>',end='')
            print(name + ':' + txl[name])
            if input('是否修改用户资料(YES/NO):').upper() == 'YES':
                txl[name] = input('请输入用户联系电话:')
        else:
            txl[name] = input('请输入用户联系电话:')
   
    elif instr == 3:
        name = input('请输入联系人姓名:')
        if name in txl:
            del(txl[name])
        else:
            print('您输入的联系人不存在。')

    elif instr == 4:
        break
    else:
        print('输入错误,重新执行程序!!!!')

print('|--- 感谢使用通讯录程序 ---|')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值