1.7基本数据类型之DICT

Python3 字典

字典是另一种可变容器模型,且可存储任意类型对象。

字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:

d = {key1 : value1, key2 : value2 }

键必须是唯一的,但值则不必。

值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

一个简单的字典实例:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

也可如此创建字典:

dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };

访问字典里的值

把相应的键放入到方括号中,如下实例:

实例

#!/usr/bin/python3
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
以上实例输出结果:
dict['Name']:  Runoob
dict['Age']:  7

如果用字典里没有的键访问数据,会输出错误如下:

实例

#!/usr/bin/python3
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'};
print ("dict['Alice']: ", dict['Alice'])
以上实例输出结果:
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print ("dict['Alice']: ", dict['Alice'])
KeyError: 'Alice'

 


修改字典

向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:

实例

#!/usr/bin/python3
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # 更新 Age
dict['School'] = "菜鸟教程" # 添加信息
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

以上实例输出结果:

dict['Age']:  8
dict['School']:  菜鸟教程

 


删除字典元素

能删单一的元素也能清空字典,清空只需一项操作。

显示删除一个字典用del命令,如下实例:

实例

#!/usr/bin/python3
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
del dict['Name'] # 删除键 'Name'
dict.clear() # 清空字典
del dict # 删除字典
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

 

但这会引发一个异常,因为用执行 del 操作后字典不再存在:

Traceback (most recent call last):
  File "test.py", line 9, in <module>
    print ("dict['Age']: ", dict['Age'])
TypeError: 'type' object is not subscriptable

注:del() 方法后面也会讨论。

 

字典键的特性

字典值可以是任何的 python 对象,既可以是标准的对象,也可以是用户定义的,但键不行。

两个重要的点需要记住:

 

1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例:

 

实例

#!/usr/bin/python3
dict = {'Name': 'Runoob', 'Age': 7, 'Name': '小菜鸟'}
print ("dict['Name']: ", dict['Name'])

 

以上实例输出结果:
dict['Name']:  小菜鸟

2)键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行,如下实例:

实例

#!/usr/bin/python3
dict = {['Name']: 'Runoob', 'Age': 7}
print ("dict['Name']: ", dict['Name'])

 

以上实例输出结果:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dict = {['Name']: 'Runoob', 'Age': 7}
TypeError: unhashable type: 'list'

 


字典内置函数&方法

Python字典包含了以下内置函数:

序号函数及描述实例
1 len(dict)
计算字典元素个数,即键的总数。
>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> len(dict)
3
2 str(dict)
输出字典,以可打印的字符串表示。
>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> str(dict)
"{'Name': 'Runoob', 'Class': 'First', 'Age': 7}"
3 type(variable)
返回输入的变量类型,如果变量是字典就返回字典类型。
>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> type(dict)
<class 'dict'>

Python字典包含了以下内置方法:

 

序号函数及描述
1 radiansdict.clear()
删除字典内所有元素
2 radiansdict.copy()
返回一个字典的浅复制
3 radiansdict.fromkeys()
创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
4 radiansdict.get(key, default=None)
返回指定键的值,如果值不在字典中返回default值
5 key in dict
如果键在字典dict里返回true,否则返回false
6 radiansdict.items()
以列表返回可遍历的(键, 值) 元组数组
7 radiansdict.keys()
返回一个迭代器,可以使用 list() 来转换为列表
8 radiansdict.setdefault(key, default=None)
和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
9 radiansdict.update(dict2)
把字典dict2的键/值对更新到dict里
10 radiansdict.values()
返回一个迭代器,可以使用 list() 来转换为列表
11 pop(key[,default])
删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
12 popitem()
随机返回并删除字典中的一对键和值(一般删除末尾对)。
1 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中

即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
a={'k1':[],'k2':[]}
c=[11,22,33,44,55,66,77,88,99,90]
for i in c:
    if i>66:
        a['k1'].append(i)
    else:
        a['k2'].append(i)
print(a)
2 统计s='hello alex alex say hello sb sb'中每个单词的个数

结果如:{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}
s='hello alex alex say hello sb sb'

l=s.split()
dic={}
for item in l:
    if item in dic:
        dic[item]+=1
    else:
        dic[item]=1
print(dic)
s='hello alex alex say hello sb sb'
dic={}
words=s.split()
print(words)
for word in words: #word='alex'
    dic[word]=s.count(word)
    print(dic)


#利用setdefault解决重复赋值
'''
setdefault的功能
1:key存在,则不赋值,key不存在则设置默认值
2:key存在,返回的是key对应的已有的值,key不存在,返回的则是要设置的默认值
d={}
print(d.setdefault('a',1)) #返回1

d={'a':2222}
print(d.setdefault('a',1)) #返回2222
'''
s='hello alex alex say hello sb sb'
dic={}
words=s.split()
for word in words: #word='alex'
    dic.setdefault(word,s.count(word))
    print(dic)



#利用集合,去掉重复,减少循环次数
s='hello alex alex say hello sb sb'
dic={}
words=s.split()
words_set=set(words)
for word in words_set:
    dic[word]=s.count(word)
    print(dic)

 

#作业一: 三级菜单
#要求:
打印省、市、县三级菜单
可返回上一级
可随时退出程序
menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '网易':{},
                'google':{}
            },
            '中关村':{
                '爱奇艺':{},
                '汽车之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龙观':{},
        },
        '朝阳':{},
        '东城':{},
    },
    '上海':{
        '闵行':{
            "人民广场":{
                '炸鸡店':{}
            }
        },
        '闸北':{
            '火车战':{
                '携程':{}
            }
        },
        '浦东':{},
    },
    '山东':{},
}



tag=True
while tag:
    menu1=menu
    for key in menu1: # 打印第一层
        print(key)

    choice1=input('第一层>>: ').strip() # 选择第一层

    if choice1 == 'b': # 输入b,则返回上一级
        break
    if choice1 == 'q': # 输入q,则退出整体
        tag=False
        continue
    if choice1 not in menu1: # 输入内容不在menu1内,则继续输入
        continue

    while tag:
        menu_2=menu1[choice1] # 拿到choice1对应的一层字典
        for key in menu_2:
            print(key)

        choice2 = input('第二层>>: ').strip()

        if choice2 == 'b':
            break
        if choice2 == 'q':
            tag = False
            continue
        if choice2 not in menu_2:
            continue

        while tag:
            menu_3=menu_2[choice2]
            for key in menu_3:
                print(key)

            choice3 = input('第三层>>: ').strip()
            if choice3 == 'b':
                break
            if choice3 == 'q':
                tag = False
                continue
            if choice3 not in menu_3:
                continue

            while tag:
                menu_4=menu_3[choice3]
                for key in menu_4:
                    print(key)

                choice4 = input('第四层>>: ').strip()
                if choice4 == 'b':
                    break
                if choice4 == 'q':
                    tag = False
                    continue
                if choice4 not in menu_4:
                    continue

                # 第四层内没数据了,无需进入下一层
menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '网易':{},
                'google':{}
            },
            '中关村':{
                '爱奇艺':{},
                '汽车之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龙观':{},
        },
        '朝阳':{},
        '东城':{},
    },
    '上海':{
        '闵行':{
            "人民广场":{
                '炸鸡店':{}
            }
        },
        '闸北':{
            '火车战':{
                '携程':{}
            }
        },
        '浦东':{},
    },
    '山东':{},
}



#part1(初步实现):能够一层一层进入
layers = [menu, ]

while True:
    current_layer = layers[-1]
    for key in current_layer:
        print(key)

    choice = input('>>: ').strip()

    if choice not in current_layer: continue

    layers.append(current_layer[choice])



#part2(改进):加上退出机制
layers=[menu,]

while True:
    if len(layers) == 0: break
    current_layer=layers[-1]
    for key in current_layer:
        print(key)

    choice=input('>>: ').strip()

    if choice == 'b':
        layers.pop(-1)
        continue
    if choice == 'q':break

    if choice not in current_layer:continue

    layers.append(current_layer[choice])
#作业二:请闭眼写出购物车程序
#需求:
用户名和密码存放于文件中,格式为:egon|egon123
启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额
import os

product_list = [['Iphone7',5800],
                ['Coffee',30],
                ['疙瘩汤',10],
                ['Python Book',99],
                ['Bike',199],
                ['ViVo X9',2499],

                ]

shopping_cart={}
current_userinfo=[]

db_file=r'db.txt'

while True:
    print('''
    1 登陆
    2 注册
    3 购物
    ''')

    choice=input('>>: ').strip()

    if choice == '1':
        #1、登陆
        tag=True
        count=0
        while tag:
            if count == 3:
                print('\033[45m尝试次数过多,退出。。。\033[0m')
                break
            uname = input('用户名:').strip()
            pwd = input('密码:').strip()

            with open(db_file,'r',encoding='utf-8') as f:
                for line in f:
                    line=line.strip('\n')
                    user_info=line.split(',')

                    uname_of_db=user_info[0]
                    pwd_of_db=user_info[1]
                    balance_of_db=int(user_info[2])

                    if uname == uname_of_db and pwd == pwd_of_db:
                        print('\033[48m登陆成功\033[0m')

                        # 登陆成功则将用户名和余额添加到列表
                        current_userinfo=[uname_of_db,balance_of_db]
                        print('用户信息为:',current_userinfo)
                        tag=False
                        break
                else:
                    print('\033[47m用户名或密码错误\033[0m')
                    count+=1

    elif choice == '2':
        uname=input('请输入用户名:').strip()
        while True:
            pwd1=input('请输入密码:').strip()
            pwd2=input('再次确认密码:').strip()
            if pwd2 == pwd1:
                break
            else:
                print('\033[39m两次输入密码不一致,请重新输入!!!\033[0m')

        balance=input('请输入充值金额:').strip()

        with open(db_file,'a',encoding='utf-8') as f:
            f.write('%s,%s,%s\n' %(uname,pwd1,balance))

    elif choice == '3':
        if len(current_userinfo) == 0:
            print('\033[49m请先登陆...\033[0m')
        else:
            #登陆成功后,开始购物
            uname_of_db=current_userinfo[0]
            balance_of_db=current_userinfo[1]

            print('尊敬的用户[%s] 您的余额为[%s],祝您购物愉快' %(
                uname_of_db,
                balance_of_db
            ))

            tag=True
            while tag:
                for index,product in enumerate(product_list):
                    print(index,product)
                choice=input('输入商品编号购物,输入q退出>>: ').strip()
                if choice.isdigit():
                    choice=int(choice)
                    if choice < 0 or choice >= len(product_list):continue

                    pname=product_list[choice][0]
                    pprice=product_list[choice][1]
                    if balance_of_db > pprice:
                        if pname in shopping_cart: # 原来已经购买过
                            shopping_cart[pname]['count']+=1
                        else:
                            shopping_cart[pname]={'pprice':pprice,'count':1}

                        balance_of_db-=pprice # 扣钱
                        current_userinfo[1]=balance_of_db # 更新用户余额
                        print("Added product " + pname + " into shopping cart,\033[42;1myour current\033[0m balance " + str(balance_of_db))

                    else:
                        print("买不起,穷逼! 产品价格是{price},你还差{lack_price}".format(
                            price=pprice,
                            lack_price=(pprice - balance_of_db)
                        ))
                    print(shopping_cart)
                elif choice == 'q':
                    print("""
                    ---------------------------------已购买商品列表---------------------------------
                    id          商品                   数量             单价               总价
                    """)

                    total_cost=0
                    for i,key in enumerate(shopping_cart):
                        print('%22s%18s%18s%18s%18s' %(
                            i,
                            key,
                            shopping_cart[key]['count'],
                            shopping_cart[key]['pprice'],
                            shopping_cart[key]['pprice'] * shopping_cart[key]['count']
                        ))
                        total_cost+=shopping_cart[key]['pprice'] * shopping_cart[key]['count']

                    print("""
                    您的总花费为: %s
                    您的余额为: %s
                    ---------------------------------end---------------------------------
                    """ %(total_cost,balance_of_db))

                    while tag:
                        inp=input('确认购买(yes/no?)>>: ').strip()
                        if inp not in ['Y','N','y','n','yes','no']:continue
                        if inp in ['Y','y','yes']:
                            # 将余额写入文件

                            src_file=db_file
                            dst_file=r'%s.swap' %db_file
                            with open(src_file,'r',encoding='utf-8') as read_f,\
                                open(dst_file,'w',encoding='utf-8') as write_f:
                                for line in read_f:
                                    if line.startswith(uname_of_db):
                                        l=line.strip('\n').split(',')
                                        l[-1]=str(balance_of_db)
                                        line=','.join(l)+'\n'

                                    write_f.write(line)
                            os.remove(src_file)
                            os.rename(dst_file,src_file)

                            print('购买成功,请耐心等待发货')

                        shopping_cart={}
                        current_userinfo=[]
                        tag=False


                else:
                    print('输入非法')


    else:
        print('\033[33m非法操作\033[0m')

 

posted on 2018-12-10 19:14  fuxu5  阅读(219)  评论(0)    收藏  举报

导航