概述
1,一维字典
1.1 定义字典
dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}
1.2 根据键值访问对应元素值
dict[‘Name’]
1.3 遍历所有键-值对
for k, v in dict.items():
1.4 遍历所有键
for k in dict.keys():
1.5 遍历所有值
for v in dict.values():
1.6 删除以’Name’为键的键-值对
del dict[‘Name’]
1.7 清空字典所有键-值对,保留空字典
dict.clear()
1.8 将整个字典从内存中抹去(空的壳也没保留)
del dict
1.9 浅拷贝一个字典
dict1 = dict.copy()
1.10 将dict2的键-值对更新到dict中
dict.update(dict2)
1.11 创建新的字典(dict.fromkeys())
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print ("New Dictionary : %s" %
str(dict))
dict = dict.fromkeys(seq, [10, 11])
print ("New Dictionary : %s" %
str(dict))
#输出为
#New Dictionary : {'name': None, 'age': None, 'sex': None}
#New Dictionary : {'name': [10, 11], 'age': [10, 11], 'sex': [10, 11]}
1.12 根据key取出value,如果没有该key,返回None或者指定的其它值
#dict.get(key, default=None)
dict = {'Name': 'Zara', 'Age': 27}
print ("Value : %s" %
dict.get('Age'))
print ("Value : %s" %
dict.get('Sex', "NA"))
#输出
#Value : 27
#Value : NA
#这一波操作后并没有将键为'Sex'的键-值对写进字典
1.13 与1.12类似,不同之处是将键为’Sex’的键-值对写进字典
dict.setdefault(key, default = None)
1.14 判断dict是否有键k
if k in dict.keys():
Note 1, 字典的键必须是可哈希的(hashable)
python中可哈希的对象:Integers, strings, tuples, immutable sets.
2,二维字典
2.1 可将二维字典的两个维放在一个元祖中,从而化解为一维字典的问题。
例:dict[‘a’][‘b’]改写为dict[(‘a’, ‘b’)]
最后
以上就是细腻纸飞机为你收集整理的python3 字典问题详解的全部内容,希望文章能够帮你解决python3 字典问题详解所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复