码迷,mamicode.com
首页 > 其他好文 > 详细

字典的方法

时间:2018-08-14 23:58:45      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:pre   字符   item   直接   默认   ict   不可   get   更新   

#字典的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互换

 

字典的方法

标签:pre   字符   item   直接   默认   ict   不可   get   更新   

原文地址:https://www.cnblogs.com/hhsh/p/9478820.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!