修炼Python基础篇-字典(Dictionary)学习
字典是另一种可变容器模型,且可存储任意类型对象,字典的每个键值(key=>value)对用冒号(:)分割,每个键值对之间用逗号(,)分割,整个字典包括在花括号({})中;
字典特性:
1.不允许同一个键出现两次,创建时如果同一个键被赋值两次,最后一个键值生效;
2.键值必须不可变,可以用数字、字符串或元组充当,因列表是可变的,所以不可以用列表做为键值;
-
访问字典中的元素;
dict ={'shanghai':'pudong','sichuan':'chengdu'}
print(dict)
{'sichuan':'chengdu','shanghai':'pudong'}
print(dict['sichuan'])
chengdu
-
修改字典中的值;
dict ={'shanghai':'pudong','sichuan':'chengdu'}
dict['sichuan']='bazhong'
print(dict['sichuan'])
bazhong
-
删除字典中的元素;
dict ={'shanghai':'pudong','sichuan':'chengdu'}
del dict['shanghai']#删除键是shanghai的值;
print(dict)
{'sichuan':'chengdu'}
dict.clear()#情况字典所有内容;
print(dict)
{}
-
len:计算字典元素个数;
dict ={'shanghai':'pudong','sichuan':'chengdu'}
print(len(dict))
2
-
str:输出字典可打印成字符串表示;
dict ={'shanghai':'pudong','sichuan':'chengdu'}
print(str(dict))
{'shanghai':'pudong','sichuan':'chengdu'}
print(type(str(dict)))
<class'str'>
-
type:返回输入的变量类型;
dict ={'shanghai':'pudong','sichuan':'chengdu'}
print(type(dict))
<class'dict'>
-
clear:删除字典内所有元素;
dict ={'shanghai':'pudong','sichuan':'chengdu'}
dict.clear()
print(dict)
{}
-
copy:浅复制一个字典;
dict ={'shanghai':'pudong','sichuan':'chengdu'}
dict1 = dict.copy()
print(dict1)
{'shanghai':'pudong','sichuan':'chengdu'}
-
fromkey:创建一个新的字典,以序列seq中的元素作为字典的键,value为字典所有键对应的初始值;
seq ='ShangHai','Beijing','SiChuan'
dict=dict.fromkeys(seq,100)
print(dict)
{'Beijing':100,'ShangHai':100,'SiChuan':100}
-
get:返回指定键的值,如果值不在字典内就返回None;
dict ={'shanghai':'pudong','sichuan':'chengdu'}
print(dict.get('shanghai'))
pudong
print(dict.get('tianjing'))
None
-
in:如果键在字典内存在就返回True,否则返回False;
dict ={'shanghai':'pudong','sichuan':'chengdu'}
print('shanghai'in dict)
True
print('jiangsu'in dict)
False
-
items:以列表方式返回可遍历的(键、值)元组数据;
dict ={'shanghai':'pudong','sichuan':'chengdu'}
print(dict.items())
dict_items([('shanghai','pudong'),('sichuan','chengdu')])
-
pop:删除指定的键值;
dict ={'shanghai':'pudong','sichuan':'chengdu'}
dict.pop('shanghai')
'pudong'
print(dict)
{'sichuan':'chengdu'}
-
popitems:随机返回并删除字典中的一对键和值(项)。为什么是随机删除呢?因为字典是无序的,没有所谓的“最后一项”或是其它顺序。在工作时如果遇到需要逐一删除项的工作,用popitem()方法效率很高。
dict ={'shanghai':'pudong','sichuan':'chengdu'}
dict.popitem()
('shanghai','pudong')
print(dict)
{'sichuan':'chengdu'}
-
setdefault:如果键不已经存在于字典中,将会添加键并将值设为默认值;
dict ={'shanghai':'pudong','sichuan':'chengdu'}
print("Value1:%s"% dict.setdefault('sichuan'))
Value1:chengdu
print("Value1:%s"% dict.setdefault('beijing'))
Value1:None
print(dict)
{'beijing': None, 'shanghai': 'pudong', 'sichuan': 'chengdu'}
-
update:把字典dict2的键、值对更新到dict里面;
dict ={'shanghai':'pudong','sichuan':'chengdu'}
dict1 ={'beijing':'chaoyang','guangdong':'shengzhen'}
dict.update(dict1)
print(dict)
{'guangdong':'shengzhen','sichuan':'chengdu','shanghai':'pudong','beijing':'chaoyang'}
-
values:以列表的方式返回字典里的值;
dict1 ={'beijing':'chaoyang','guangdong':'shengzhen'}
print(dict.values())
dict_values(['shengzhen','chengdu','pudong','chaoyang'])