飞道的博客

Python学习之路-----字典操作

331人阅读  评论(0)

字典

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

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

dict = {key1 : value, key2 : value2,.....}

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

值可以取任意数据类型,但是键只能取不变数据类型(元组、字符串、数字)

创建字典

my_dict = {'name' : 'YWH', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169]}

访问字典里的值

把需要访问的值的相应的键放入方括号[ ]中

#如果对字典里没有的键进行访问,则会输出错误如下:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print ("dict['Alice']: ", dict['Alice'])
KeyError: 'Alice'
my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169]}
print('My name is %s:'%my_dict['name'])
print('My year is %d:'%my_dict['year'])
if my_dict['gender'] == 1:
	print("I am a Boy!")
else
	print('I am a Girl!')
	
'''
My name is Yuwenhao
My year is 21
I am a Boy!
'''

修改字典

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169]}
print('My year is %d:'%my_dict['year'])

my_dict['year'] = 22
my_dict['School'] = 'HZAU'
print('Now, My year is %d:'%my_dict['year'])
print('My school is %s:'%my_dict['School'])

'''
My year is 21:
Now, My year is 22:
My school is HZAU:
'''

删除字典

能删除单一的元素也能清空字典

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169]}

del my_dict['name']
my_dict.clear()   #清空一个字典
print(my_dict)

del my_dict
print(my_dict)    #删除一个字典

'''
{}    
Traceback (most recent call last):
  File "F:\Python\Program\test.py", line 8, in <module>
    print(my_dict)
NameError: name 'my_dict' is not defined
'''

字典的键

1)字典不允许同一个键出现两次。创建时如果痛一个键被赋值两次,后一个值将会被记住

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169],'name':'YWH'}

print("my name is",my_dict['name'])
print("my dist is",my_dict)
'''
my name is YWH
my dist is {'name': 'YWH', 'year': 21, 'gender': 1, 'address': ['Xinghuajie', 169]}
'''

2)键必须是不可变数据类型

error_dist = {['name'] : 'Ywh'}
print("my name is",error_dist['name'])

'''
Traceback (most recent call last):
  File "F:\Python\Program\test.py", line 1, in <module>
    error_dist = {['name'] : 'Ywh'}
TypeError: unhashable type: 'list'
'''

字典内置函数

len(dict) 计算字典元素的个数(键的个数)

str(dict) 输出字典,以可打印的字符串表示

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169]}

str(my_dict)

'''
"{'name': 'Yuwenhao', 'year': 21, 'gender': 1, 'address': ['Xinghuajie', 169]}"
'''

字典的方法

dict.clear() 删除字典内所有元素

dict.copy() 返回字典的一个浅复制

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169]}

copy_dict = {}
copy_dict = my_dict.copy()

print(copy_dict)

'''
{'name': 'Yuwenhao', 'year': 21, 'gender': 1, 'address': ['Xinghuajie', 169]}
'''

dict.fromkeys(seq, value) 创建一个新字典,以序列seq中的元素作为字典的键,value作为字典所有键对应的初始值,默认为None

my_dict = {}
seq = ('name','year','gender')
my_dict = my_dict.fromkeys(seq)
print(my_dict)
my_dict = my_dict.fromkeys(seq,100)
print(my_dict)

'''
{'name': None, 'year': None, 'gender': None}
{'name': 100, 'year': 100, 'gender': 100}
'''

key in dict 如果键在字典里返回True

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Henan','Zhengzhou','Erqi','Xinghuajie',169]}

print('name' in my_dict)
print('color' in my_dict)

'''
True
False
'''

dict.items() 以列表返回可便利的(键、值)元组数组

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1, 'address' : ['Xinghuajie',169]}

list = my_dict.items()

print(list)

'''
dict_items([('name', 'Yuwenhao'), ('year', 21), ('gender', 1), ('address', ['Xinghuajie', 169])])
'''

dict.keys() 返回一个迭代器,可以使用list()来转换为列表

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1}
iterator = my_dict.keys()
print(iterator)
iterator_list = list(my_dict.keys())
print(iterator_list)

'''
dict_keys(['name', 'year', 'gender'])
['name', 'year', 'gender']
'''

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

dict.update(dict2) 把dict2中的键值对更新到dict中去

dict.values() 返回一个迭代器,可以使用list()来转换为列表

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1}
iterator = my_dict.values()
print(iterator)
iterator_list = list(my_dict.values())
print(iterator_list)

'''
dict_values(['Yuwenhao', 21, 1])
['Yuwenhao', 21, 1]
'''

dist.pop(key,default) 删除字典给的键key所对应的值,返回值为被删除的值。key值必须给出!!不然会报错。如果要删除的 key 不存在,则需要添加默认值,否则会报错:

my_dict = {'name' : 'Yuwenhao', 'year' : 21, 'gender' : 1}
print(my_dict.pop('name'))
print(my_dict.pop('color','None'))

'''
Yuwenhao
None
'''

dict.popitem() 随机返回并删除字典中的最后一对键和值


转载:https://blog.csdn.net/qq_42642142/article/details/106169698
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场