字典的方法

Posted hhsh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字典的方法相关的知识,希望对你有一定的参考价值。

#字典的KEY只能是不可变数据类型:(int bool 字符串 元祖) (可变数据类型:list dict set)
# dic = {1: 1, ‘age‘: 18, ‘name‘: ‘huang‘, (1, 2): ‘abc‘}
# print(dic)

#
# dic = {‘name‘: ‘huang‘, ‘age‘: 26, ‘work‘: ‘IT‘,}
# dic[‘sex‘] = ‘male‘            #没有KEY,添加
# dic[‘age‘] = 16                #如果有key,则值覆盖
# print(dic)

# dic.setdefault(‘weight‘)            #没有KEY,添加,默认是None
# dic.setdefault(‘weight‘, 50)        #已经有KEY就不改变
# print(dic)


#
# dic = {‘name‘: ‘huang‘, ‘age‘: 26, ‘work‘: ‘IT‘}
# print(dic.pop(‘name‘))             #删除KEY时返回的是value,如果KEY不存在则出错
# print(dic.pop(‘age‘, None))        #删除KEY时返回的是value,如果KEY不存在则返回None而不会出错
# print(dic)

# dic = {‘name‘: ‘huang‘, ‘age‘: 26, ‘work‘: ‘IT‘}
# del dic
# print(dic)

# dic = {‘name‘: ‘huang‘, ‘age‘: 26, ‘work‘: ‘IT‘}
# print(dic.clear())                  #清空


#
# dic = {‘name‘: ‘huang‘, ‘age‘: 26, ‘work‘: ‘IT‘}
# dic[‘age‘] = 33              #直接改已存在的KEY值
# print(dic)

# dic = {‘name‘: ‘huang‘, ‘age‘: 26, ‘work‘: ‘IT‘}
# dic2 = {‘name‘: ‘haisheng‘, ‘sex‘: ‘male‘, ‘birth‘: 1992}
# dic.update(dic2)                  #如果KEY相同则更新value,否则更新所有新的键值对
# print(dic)


#
# dic = {‘name‘: ‘huang‘, ‘age‘: 26, ‘work‘: ‘IT‘}
# print(dic.keys())               #打印KEY,返回列表[‘name‘, ‘age‘, ‘work‘]
# print(dic.values())             #打印字典的值[‘huang‘, 26, ‘IT‘]
# print(dic.items())              #打印字典的项[(‘name‘, ‘huang‘), (‘age‘, 26), (‘work‘, ‘IT‘)]

# for k in dic:                  # 相当于 for k in dic.keys():
#     print(k)
#
# for v in dic.values():         #返回value
#     print(v)
#
# for i in dic.items():          #返回的是元祖 (‘name‘, ‘huang‘)
#     print(i)

# for k, v in dic.items():         #返回的是键值对应关系
#     print(k, v)

# v = dic[‘age‘]                 #查字典的KEY对应的值,如果没有KEY则报错
# print(v)
#
# v = dic.get(‘age1‘, None)       #查字典的KEY对应的值,如果没有KEY则不报错,返回None
# print(v)

#a, b = 1, 2
#a, b =b, a a和b互换

 




以上是关于字典的方法的主要内容,如果未能解决你的问题,请参考以下文章

Python代码阅读(第19篇):合并多个字典

Python代码阅读(第26篇):将列表映射成字典

Python代码阅读(第40篇):通过两个列表生成字典

VSCode自定义代码片段—— 数组的响应式方法

VSCode自定义代码片段10—— 数组的响应式方法

Android课程---Android Studio使用小技巧:提取方法代码片段