16.字典

目录

一、字典的创建

1.字典的格式

2.创建空字典

3.字典中键的类型

4.创建字典的N中方法

5.zip函数

二、字典的增删改查

1.在字典中增加键值对

2.字典的删除操作

3.修改字典

4.字典的查询操作

三、练习

1.字典基本练习

2.找到b值

3.词频统计

4.探寻身份证号

四、第十四课练习答案


字典是Python中最灵活的内置数据类型之一。如果你把列表看作是对象的有序集合,你可以把字典看作是无序的集合。

在字典中,元素是按照键名存储和提取的,而不像列表或元组按照索引存储和提取。

在字典中,元素所属键的名称比所在的位置更有意义。

一、字典的创建

1.字典的格式

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

dict = {key1 : value1, key2 : value2 }
stud_info = {name:'Jim',old:18,sex:'male'}

2.创建空字典

# 方法一:
D = {}

# 方法二:
D = dict()

3.字典中键的类型

字典中值的可以是任意类型,而字典中的键必须是不可变的,如字符串、数字或元组。

# 使用字符串作为键
options = {'a':'1+x','b':'1-x','c':'|x|','d':'x*x'} 

# 使用数字作为键
menu_10086 = {1:'业务查询',2:'交话费享折扣',3:'业务办理',4:'宽带业务办理',0:'人工服务'}

# 使用元组作为键
RGB = {(0,0,0):'黑色',(0,0,255):'蓝色',(0,255,0):'绿色',(0,255,255):'青色',(255,0,0):'红色',(255,0,255):'亮紫色(洋红色)',(255,255,0):'黄色',(255,255,255):'白色'}

4.创建字典的N中方法

# 方法一 直接指定键值对
D = {'name':'Tom','old':20,'sex':'male'}
print(D)

# 方法二 使用关键字dict和参数赋值
D = dict(name='Tom',old=20,sex='male')
print(D)

# 方法三 使用二元组列表创建
D= dict([('name','Tom'),('old',20),('sex','male')])
print(D)

# 方法四 使用关键字dict和zip函数
keylist = ['name','sex','old']
valuelist = ['Jone','male',21]
D = dict(zip(keylist,valuelist))
print(D)

# 输出
{'name': 'Tom', 'old': 20, 'sex': 'male'}
{'name': 'Tom', 'old': 20, 'sex': 'male'}
{'name': 'Tom', 'old': 20, 'sex': 'male'}
{'name': 'Jone', 'sex': 'male', 'old': 21}

# 方法五 使用dict.fromkeys方法
D = dict.fromkeys(['name','old','job'])
print(D)
# 输出
{'name': None, 'old': None, 'job': None}

D['name'] = 'jim'
for i,v in D.items():
    print(id(D[i]))
print(D)

# 输出
4479295200
4479295200
4479295200
{'name': 'jim', 'old': None, 'job': None}

for i,v in D.items():
    print(id(D[i]))

D = dict.fromkeys(['name','old','job'],[])
D['name'].append('jim')
print(D)

# 输出
4482470448
4479295200
4479295200
{'name': ['jim'], 'old': ['jim'], 'job': ['jim']}

5.zip函数

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个可迭代的对象。

# Python3.X 中 zip函数返回一个可迭代的zip对象
print(zip([1,2,3],['a','b','c']))
# 输出
<zip object at 0x10bb7c5c0>

# 使用list函数输出
print(list(zip([1,2,3],['a','b','c'])))
# 输出
[(1, 'a'), (2, 'b'), (3, 'c')]

# 使用dict函数输出
print(dict(zip([1,2,3],['a','b','c'])))
# 输出
{1: 'a', 2: 'b', 3: 'c'}

使用zip函数和*一起使用可以解压缩列表,实现对zip的逆操作。

x = [1,2,3]
y = [4,5,6]
zipped = zip(x,y)
print(zipped)
list_zipped = list(zipped)
print(list_zipped)

print(list(zip(*list_zipped)))

x1,y1 = zip(*list_zipped)
print(x1)
print(y1)

# 输出
<zip object at 0x101951a80>
[(1, 4), (2, 5), (3, 6)]
[(1, 2, 3), (4, 5, 6)]
(1, 2, 3)
(4, 5, 6)


m = [[1, 2, 3],  [4, 5, 6],  [7, 8, 9]]
n = [[2, 2, 2],  [3, 3, 3],  [4, 4, 4]]

zipped1 = list(zip(m,n))
print(zipped1)

m1,n1 = zip(*zipped1)
print(m1)
print(n1)

# 输出
[([1, 2, 3], [2, 2, 2]), ([4, 5, 6], [3, 3, 3]), ([7, 8, 9], [4, 4, 4])]
([1, 2, 3], [4, 5, 6], [7, 8, 9])
([2, 2, 2], [3, 3, 3], [4, 4, 4])

二、字典的增删改查

1.在字典中增加键值对

D = {}
D['color_1'] = 'red'
D['color_2'] = 'orange'
D['color_3'] = 'yellow'
print(D)
D['colors'] = ['red','orange','yellow','green',]
print(D)


# 输出
{'color_1': 'red', 'color_2': 'orange', 'color_3': 'yellow'}
{'color_1': 'red', 'color_2': 'orange', 'color_3': 'yellow', 'colors': ['red', 'orange', 'yellow', 'green']}

2.字典的删除操作

(1)使用del函数

# 使用del函数
del D['color_1']
print(D)

# 输出
{'color_2': 'orange', 'color_3': 'yellow', 'colors': ['red', 'orange', 'yellow', 'green']}

(2)使用pop()

# 使用dict.pop(key[,default])方法,pop方法根据指定的键名删除字典中的键值对,并返回value
print(D.pop('color_2'))
print(D)
# 输出
orange
{'color_3': 'yellow', 'colors': ['red', 'orange', 'yellow', 'green']}

# 在不指定default值时,如果删除的键不存在,则会出现keyerror
print(D.pop('color_4'))
# 输出
Traceback (most recent call last):
  File "/Users/binhu/PycharmProjects/learnpython/test.py", line 11, in <module>
    print(D.pop('color_4'))
KeyError: 'color_4'

# 在指定default值为None,如果删除的键不存在,则会返回None
print(D.pop('color_4',None))

# 输出
None

(3)使用popitem()

D = {'a':1,'b':2,'c':3,'d':4,'e':5}
print(D)

print(D.popitem())
print(D)

print(D.popitem())
print(D)

# 输出:
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
('e', 5)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
('d', 4)
{'a': 1, 'b': 2, 'c': 3}

3.修改字典

D = {'color_3': 'yellow', 'colors': ['red', 'orange', 'yellow', 'green']}
D['color_3'] = 'pink' # 如果键存在则更新该键的值,如果不存在则添加该键值对
print(D)
D['colors'].append('cyan') # 向字典中的嵌套列表添加元素
print(D)

for value in ['blue','purple']:
    D['colors'].append(value) # 向字典中的嵌套列表批量添加元素
print(D)

D['quantity'] = 18 # 添加'quantity':18键值对
for i in range(5):
    D['quantity'] += i # 循环更新'quantity'的值
    print(D)

# 输出:
{'color_3': 'pink', 'colors': ['red', 'orange', 'yellow', 'green']}
{'color_3': 'pink', 'colors': ['red', 'orange', 'yellow', 'green', 'cyan']}
{'color_3': 'pink', 'colors': ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple']}
{'color_3': 'pink', 'colors': ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple'], 'quantity': 18}
{'color_3': 'pink', 'colors': ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple'], 'quantity': 19}
{'color_3': 'pink', 'colors': ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple'], 'quantity': 21}
{'color_3': 'pink', 'colors': ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple'], 'quantity': 24}
{'color_3': 'pink', 'colors': ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple'], 'quantity': 28} 

使用updata()修改字典:格式:dict.update(dict2)

 update() 函数把字典dict2的键/值对更新到dict里。

# 情形一:如果键存在则更新键的值
a = {1: 2, 2: 2}
b = {1: 1, 3: 3}
b.update(a)
print b

# 输出
{1: 2, 2: 2, 3: 3}

# 情形二:如果键不存在,则插入新值
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }

dict.update(dict2)
print("Value : %s" %  dict)

# 输出:
Value : {'Name': 'Zara', 'Age': 7, 'Sex': 'female'}

4.字典的查询操作

(1)dict.keys()

keys() 方法返回一个可迭代对象,可以使用 list() 来转换为列表。

dict = {'Name': 'Zara', 'Age': 7, 'Sex': 'female'}

print(dict.keys())

for key in dict.keys():
    print(key)

# 输出
dict_keys(['Name', 'Age', 'Sex'])
Name
Age
Sex

(2)dict.values()

dict = {'Name': 'Zara', 'Age': 7, 'Sex': 'female'}

print(dict.values())

for value in dict.values():
    print(value)

# 输出
dict_values(['Zara', 7, 'female'])
Zara
7
female

(3)dict.items()

dict = {'Name': 'Zara', 'Age': 7, 'Sex': 'female'}

print(dict.items())

for key,value in dict.items():
    print(key,value)

# 输出
dict_items([('Name', 'Zara'), ('Age', 7), ('Sex', 'female')])
Name Zara
Age 7
Sex female

(4)len()

dict = {'Name': 'Zara', 'Age': 7, 'Sex': 'female'}
print(len(dict))

输出:
3

(5)dict.get(key,default = None)

返回指定键的值,如果值不在字典中返回default值,默认为None

dict = {'Name': 'Zara', 'Age': 7, 'Sex': 'female'}
print(dict.get('Name'))

print(dict.get('Job'))

# 输出
Zara
None

(6)dict.setdefault(key,default = None)

和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default

dict = {'Name': 'Zara', 'Age': 7, 'Sex': 'female'}
print(dict.setdefault('Name'))

dict.setdefault('Job','developer')
print(dict)

# 输出
Zara
{'Name': 'Zara', 'Age': 7, 'Sex': 'female', 'Job': 'developer'}

三、练习

1.字典基本练习

dic = {
    'python': 95,
    'html/css': 99,
    'c': 100
}

‘’‘
1.字典的长度是多少
2.请修改'html/css' 这个key对应的value值为98
3.删除 c 这个key
4.增加一个key-value对,key值为 php, value是90
5.获取所有的key值,存储在列表里
6.获取所有的value值,存储在列表里
7.判断 javascript 是否在字典中
8.获得字典里所有value 的和
9.获取字典里最大的value
10.获取字典里最小的value
11.字典 dic1 = {'php': 97}, 将dic1的数据更新到dic中
’‘’

2.找到b值

字典D中有17个键值对,每个键值对以(a,b):v的方式存储,要求编写一段程序,找出满足a==10,v==1条件时b的值。

D = {(4, 7): 0, (2, 6): 1, (10, 4): 1, (5, 11): 1, (4, 5): 1,
(2, 8): 0, (8, 11): 0, (10, 0): 1, (6, 11): 1, (9, 11): 1,
(1, 9): 0, (10, 1): 0, (7, 11): 1, (0, 9): 1, (3, 7): 1,
(10, 3): 1, (10, 2): 1}

3.词频统计

# <apologize> 歌词
words = '''
I'm holding on your rope
Got me ten feet off the ground
And I'm hearing what you say
But I just can't make a sound
You tell me that you need me
Then you go and cut me down
But wait
You tell me that you're sorry
Didn't think I'd turn around and say
That it's too late to apologize
It's too late
I said it's too late to apologize
It's too late
I'd take another chance take a fall
Take a shot for you
I need you like a heart
Needs a beat
But it's nothing new
I loved you with the fire red
Now it's turning blue and you say
Sorry like the angel
Heaven let me think was you
But I'm afraid
It's too late to apologize
I said it's too late to apologize
It's too late to apologize
I said it's too late to apologize
I said it's too late to apologize yeah
I said it's too late to apologize yeah
I'm holding on your rope got me ten feet off the ground
'''


# 任务1:将所有大写转换为小写

# 任务2:生成单词列表

# 任务3:生成词频统计

# 任务4:排序

# 任务5:排除语法型词汇,代词、冠词、连词

# 任务6:输出词频最大TOP20

4.探寻身份证号

身份证号包含着许多信息,第7到14位是生日信息,倒数第二位是性别代码,男性为奇数,女性为偶数。要求将account列表中的三个元素按照info字典的格式输出。

account = ['Jone360403200105070312','Tom36040320020903043X','Susan360101200108110181']
‘’‘
info = {
    'Jone':{
        '生日':'2001年5月7日',
        '性别':'男'
    },
    'Tom':{
        '生日':'2002年9月3日',
        '性别':'男'
    },
    'Susan':{
        '生日':'2001年8月11日',
        '性别':'女'
    }
}
’‘’

四、第十四课练习答案

1.列表基础练习

'''
lst = [2, 5, 6, 7, 8, 9, 2, 9, 9]

完成以下任务:
1.在列表的最后插入100
2.将30插入到列表的中间位置
3.将索引为3的元素删除
4.将[22,33,44]合并到列表的最后
5.将列表中的元素从大到小、从小到大各排序一次。
'''
lst = [2, 5, 6, 7, 8, 9, 2, 9, 9]
lst.append(100)
lst.insert(len(lst)//2,30)
lst.pop(3)
lst.extend([22,33,44])
lst.sort(reverse=True)
lst.sort(reverse=False)
print(lst)

2.列表复杂练习

'''
lst	= [11, 22, 33, [44, 55, 66, 77, [88, 99, 100, 110]]]
编程完成以下任务:
1.输出lst的长度
2.输出lst中元素的和
3.将55修改为5555
4.输出99
5.将[7788,8899]插入到66的后面
6.找出列表中所有元素的最大值

在完成以上操作后,思考回答以下问题:
1.lst[-1][-1][-2]是什么? 100
2.len(lst[-1][-1])是多少? 4
3.lst[-1][1:3]是什么? [5555, 66]
4.lst[-1][-1][1:-2]是什么?[99]
'''
# 问题一
lst	= [11, 22, 33, [44, 55, 66, 77, [88, 99, 100, 110]]]
print(len(lst))

# 问题二
def flatten(li):
    return sum(([x] if not isinstance(x, list) else flatten(x) for x in li), [])

print(sum(flatten(lst)))

# 问题三
lst[3][1]=5555
print(lst[-1][-1][-3])

# 问题四
lst[-1].insert(3,[7788,8899])
print(lst)

# 问题五
print(max(flatten(lst)))

3.有一个已经排好序的列表[23, 24, 30, 32, 40, 46, 61, 65, 87, 96],用户随机输入一个数,将它按原有规律插入列表中。

lst = [23, 24, 30, 32, 40, 46, 61, 65, 87, 96]
number = int(input("请输入一个整数"))
if lst[0] > lst[-1]:
    for i in range(len(lst)):
        if number > lst[i]:
            lst.insert(i,number)
            break
        else:
            continue
else:
    for i in range(len(lst)):
        if number < lst[i]:
            lst.insert(i,number)
            break
        else:
            continue
print(lst)

4. products =  [["iphone12(128G)",6799],["Macbook air",9799],["HUAWEI P40 Pro",7988],["Moccona #8 Coffee",109],["Fluent Python Book",95],["Nike",699]],需打印出以下格式。

‘’‘
----------  商品列表 ----------
0 iphone12(128G)        6799
1 Macbook air           9799
2 HUAWEI P40 Pro        7988
3 Moccona #8 Coffee      109
4 Fluent Python Book      95
5 Nike                   699
’‘’

products = [["iphone12(128G)",6799],["Macbook air",9799],["HUAWEI P40 Pro",7988],["Moccona #8 Coffee",109],["Fluent Python Book",95],["Nike",699]]
print("----------  商品列表 ----------")
for index in range(len(products)):
    print(index,products[index][0],str(products[index][1]).rjust(26-len(str(index))-len(products[index][0])))

5.在上题基础上,编写一个程序,实现不断询问用户想买什么,提示用户输入商品编号,就把对应的商品添加到购物车里,同时显示当前购物车中的商品列表和总价格,最终用户输入q退出时,打印购买的商品列表及总价格。

user_productlist = []
while True:
    user_info = input("what do you want?please insert product id,press 'q' to exit.")
    if user_info == 'q':
        print("-------- 你选择的商品列表 --------")
        for index in range(len(user_productlist)):
            print(index, user_productlist[index][0], str(user_productlist[index][1]).rjust(26 - len(str(index)) - len(user_productlist[index][0])))
        print(sum([x[1] for x in user_productlist]))
        break
    elif int(user_info) in list(range(6)):
        user_productlist.append(products[int(user_info)])
        print("-------- 你选择的商品列表 --------")
        for index in range(len(user_productlist)):
            print(index, user_productlist[index][0], str(user_productlist[index][1]).rjust(26 - len(str(index)) - len(user_productlist[index][0])))
        print(sum([x[1] for x in user_productlist]))
        continue
    else:
        print("please correct product id")
        continue
print(user_productlist)

猜你喜欢

转载自blog.csdn.net/qq_40407729/article/details/111408052