python全栈闯关--5-字典

1、数据类型的划分

数据类型分为:可变数据类型,不可变数据类型

    • 不可变数据类型:元祖、bool、int、str                    可哈希
    • 可变数据类型:list,dic,set                                   不可哈希

2、dic的数据结构

dic key:必须为可哈希数据类型,不可以变数据类型

      value:任意数据类型

dic 优点:二分查找,存储大量关系型数据

dic特点:3.6以前无序,3.6后有序

 

3、dic的增、删、改、查

定义
dic = {
    'name': ['bear', 'Honey', 'bee'],
    'myPthon': [{'num1': 71, 'avg_age': 18}
                ,{'num1': 71, 'avg_age': 18}
                ,{'num1': 71, 'avg_age': 18}],
    True: 1,
    (1, 2, 3): 'bee',
    2: 'Honey'
}
print(dic)

The key value is an immutable type(hash),which can be tuple,bool,int,str. (immutable:不可变)

 But when the key value is a tuple, it must be an immutable type.

A varable tuple like this is not posible:(1, 2, 3, [1, 2]).

It will reopot errors:TypeError: unhashable type: 'list'.

dic1 = {'age': 18, 'name': 'bear', 'sex': 'male'}
dic2 = {}
# if the key value does not exist to be added to the dictionary
dic1['high'] = 185
# if the dictionary has a key value, update the corresponding value to the dictionary (corresponding:相符的)
dic1['age'] = 15

# Key value does not exist, default add none to dictionary
dic1.setdefault('weight')
# The key value does note exist, if the second parameter is specified,add the (key,value) pair to the dictionary
dic1.setdefault('weight', 90)
# If the key value already exists,the specified value will not be update to the dictionary
dic1.setdefault('name', 'bee')

有返回值的删除:

# 返回键值对应的值,并删除,键值不存在将会报错
print(dic1.pop('age'))  # 15
# 指定键值不存在时返回None,可以指定任务值
print(dic1.pop('age', None))  # None

# 随机删除,返回值为(key,value)的形势
print(dic1.popitem())  # ('weight', None)

del

# 删除键值对应的数据,无键值报错KeyError:
del dic1['name']
print(dic1)

# 内存中删除整个字典
del dic1
print(dic1)  # NameError: name 'dic1' is not defined

 

clear

# 清空字典
dic1.clear()
print(dic1)  # {}
# 跟del不同,clear只是清空,字典不从内存中删除

 

#
# 直接赋值
dic1['age'] = 19

# update
# 使用字典2中的值合并到字典1,键值相同更新,不同新增
dic2 = {'name': 'honey bee', 'inters': ['swing', 'sing'], 'Habit': 'Watch movie'}
dic1.update(dic2)
print(dic1)
print(dic2)
# 打印key值,value值,(key,value)值
print(dic1.keys(), type(dic1.keys()))
print(dic1.values())
print(dic1.items())
# 加keys和直接使用字典名,都是打印key值
for i in dic1:
    print(i)
for i in dic1.keys():
    print(i)

# 打印字典的value值
for i in dic1.values():
    print(i)

 

# One line of code exchanges value of a and b
a = 1
b = 2
a, b = b, a
print(a, b)
# 同时获取key和value值
for k, v in dic1.items():
    print(k, v)
# 键值不存在报错,可以使用get,指定键值不存在的时候,返回值
v1 = dic1['age']
print(v1)
print(dic1.get('name1', '没有这个键'))

 

4、dic的嵌套

dic1 = {'name': ['bear big', 'bear two', 'strong bald head']
        ,'py9': {
            'time': '0910',
            'learn_money': 12300,
            'addr':'CBD'
          },
        'age': 29
        }

print(dic1)
# 更爱age键值为56
dic1['age'] = 56
print(dic1)

# 键值name对应的是列表,列表添加值
print(dic1['name'])
dic1['name'].append('honey bee')
print(dic1['name'])

# 键值name对应的index1的值最大
dic1['name'][1] = dic1['name'][1].upper()
print(print(dic1['name']))

# 求出输入字符串中,有几个数字
info = input(">>>") # fhdklah123rfdj12fdjsl3
for i in info:
    if i.isalpha():
        info = info.replace(i, ' ')
l = info.split()  # 这里不能用l = info.split(' '),否则每个空格都会分出一个元素
print(l)
print(len(l))

 

 

6、练习

'''
3、元素分类
    有如下值li= [11,22,33,44,55,66,77,88,99,90],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66的所有值列表, 'k2': 小于66的所有值列表}


'''
li = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
li_greater = []
li_less = []
dic = {}

for i in li:
    if i == 66: continue
    if i > 66:
        li_greater.append(i)
    else:
        li_less.append(i)

dic.setdefault('k1', li_greater)
dic.setdefault('k2', li_less)
print(dic)
'''
4、输出商品列表,用户输入序号,显示用户选中的商品
    商品 li = ["手机", "电脑", '鼠标垫', '游艇']
要求:1:页面显示 序号 + 商品名称,如:
          1 手机
           2 电脑
              …
     2: 用户输入选择的商品序号,然后打印商品名称
  3:如果用户输入的商品序号有误,则提示输入有误,并重新输入。
4:用户输入Q或者q,退出程序。

'''
li = ["手机", "电脑", '鼠标垫', '游艇']

while True:
    for k, v in enumerate(li):
        print('{}\t{}'.format(k + 1, v))
    choice = input("请选择商品(输入Q/q退出):")
    if choice.isdigit():
        choice = int(choice)
        if 0 < choice <= len(li):
            print("你选择了商品:", end='')
            print("%s\t%s" % (str(choice), li[choice - 1]))
        else:
            print("输入有误,请重新输入!")
    elif choice.upper() == 'Q':
        break
    else:
        print("请输入数字!")

 

转载于:https://www.cnblogs.com/zxw-xxcsl/p/11478580.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值