标签:03 dic dic1 dict key print 字典
1,字典的创建三种方式、
方式一
dic1 = dict((('one', 1), ('two', 2), ('tree', 3))) # 利用dict函数将元组转化为字典
print(dic1) #
方式二
dic2 = dict(one=1, two=2, tree=3) # 利用dict函数将键值对转化为字典
print(dic2) #
方式三
dic3 = dict({'one':1,'two':2,'tree':3})
print(dic3) #
dic1 =
print(dic1)
# len() 求长度
print(len(dic1))
增,改
dic1['sex'] = '女' # 改
print(dic1)
dic1['weight'] = '50kg' # 增(有则修改,无则添加)
print(dic1)
setdefault()
dic1.setdefault('hobby', '球类运动')
dic1.setdefault('sex', 20) # 已经有age不会改变
print(dic1) #
*删 del,pop(),clear()
del.dic1['weight'] # 删
print(dic1)
ren1 = dic1.pop('age') # 删
ren2 = dic1.pop('hobby','没有此键')
print(ren2) # 没有此键
print(dic1)
dic1.clear() # 清空字典
print(dic1) # {}
print(dic1['name']) # 查
*get()
s1 = dic1.get('hobby','没有此键') # 用来查找
print(s1) # 没有此键
print(dic1.get('id', 'id不存在')) # 查寻时如果没有可以返回指定的语句而不报错
update 的用法--有主键就更新,没有主键就添加
dic1.update({'weight': 50}) # 添加
print(dic1)
dic1.update(weight=60) # 更新
print(dic1)
fromkeys
dic = dict.fromkeys('abc',100) #
dic = dict.fromkeys([1, 2, 3], [])
dic[1].append(666) # {1: [666], 2: [666], 3: [666]} 共用一个,一个变全都变
print(dic)
print(dic1.keys()) # 返回字典的键值
for key in dic1.keys():
print(key)
print(dic1.values()) # 返回字典的值
for value in dic1.values():
print(value)
print(dic1.items()) # 返回字典的所有值 生成列表
for i in dic1.items():
print(i)
======================================================================================================================
批量删除
dic =
把主键含有‘k’的元素删除
方法一
l1 = []
for key in dic:
if 'k' in key:
l1.append(key)
for i in l1:
dic.pop(i)
print(dic)
方法二
for key in list(dic.keys()):
if 'k' in key:
dic.pop(key)
print(dic)
循环一个字典时,如果这个改变字典的大小,就会报错。
s1 = '中国'
s2 = s1.encode('utf-8')
print(s1)
print(s2)
a1 = b'\xe4\xb8\xad\xe5\x9b\xbd'
a2 = a1.decode('utf-8')
print(a2)
标签:03,
dic,
dic1,
dict,
key,
print,
字典
From: https://www.cnblogs.com/Marker-411528/p/18115333