#Auther Bob
#–*–conding:utf-8 –*–
#创建一个字典dict
dic1 = {‘k1′:’v1′,’k2′:’v2’}
dic2 = dict(k1=’v1′,k2=’v2′)
print(type(dic1),type(dic2))
# <class ‘dict’> <class ‘dict’>
print(dic1)
print(dic2)
# {‘k1’: ‘v1’, ‘k2’: ‘v2’}
# {‘k1’: ‘v1’, ‘k2’: ‘v2’}
#clear,清空字典所有的元素
dic1.clear()
print(dic1)
# {}
#copy,这个copy也是浅拷贝
dict3 = dic2.copy()
print(dict3)
# {‘k1’: ‘v1’, ‘k2’: ‘v2’}
# fromkeys,可以生成一个新的dict
new_dict = dict.fromkeys([‘k1′,’k2′,’k3′],’v’)
print(new_dict)
# {‘k1’: ‘v’, ‘k2’: ‘v’, ‘k3’: ‘v’}
#get,获取dict中的元素,如果对应的key存在,则返回该key对应的value值,如果不存在
#则返回none
test_dict = {‘name’:’Bob’,’age’:12,’job’:’it’}
result = test_dict.get(‘name’)
print(result)
# Bob
result = test_dict.get(‘home’)
print(result)
# None
# items,返回dict中的key和value的值
result = test_dict.items()
print(result)
# dict_items([(‘name’, ‘Bob’), (‘age’, 12), (‘job’, ‘it’)])
# keys,返回dict的key
result = test_dict.keys()
print(result)
# dict_keys([‘name’, ‘age’, ‘job’])
for k in test_dict.keys():
print(k)
# name
# age
# job
# values,返回dict的value的值
result = test_dict.values()
print(result)
# dict_values([‘Bob’, 12, ‘it’])
for v in test_dict.values():
print(v)
# Bob
# 12
# it
# pop,删除某个dict的key,会把删除key的value返回,我们可以捕获到
result = test_dict.pop(‘job’)
print(test_dict)
# {‘age’: 12, ‘job’: ‘it’}
print(result)
# it
# popitem,会随机删除一个key
test_dict = {‘name’:’Bob’,’age’:12,’job’:’it’}
test_dict.popitem()
print(test_dict)
# {‘name’: ‘Bob’, ‘age’: 12}
#setdefault,给字典设置默认的key的value的值为none,如果key的value的值存在,则不会设置
#如果没有对应的key值,则会设置一个默认值none
test_dict.setdefault(‘name’)
print(test_dict)
# {‘name’: ‘Bob’, ‘age’: 12}
test_dict.setdefault(‘home’)
print(test_dict)
# {‘name’: ‘Bob’, ‘age’: 12, ‘home’: None}
setdefault的作用
有一个字典已经有多个元素,
test_dict.setdefault(“k3″,”v3”)
这个的意思 如果字典中有k3这个k值,且有值,则这段代码不会有任何作用,但是如果字典中没有k3这个k值,则会增加一个k为k3的值,且k3的values的值为v3
# update,更新字典
test_dict = {‘name’:’Bob’,’age’:12,’job’:’it’}
dic1 = {‘k1′:’v1′,’k2′:’v2’}
test_dict.update(dic1)
print(test_dict)
# {‘name’: ‘Bob’, ‘age’: 12, ‘job’: ‘it’, ‘k1’: ‘v1’, ‘k2’: ‘v2’}
dic1.update({‘k3′:’v3’})
print(dic1)
# {‘k1’: ‘v1’, ‘k2’: ‘v2’, ‘k3’: ‘v3’}
#来一个练习题,有如下集合,[11,22,33,44,55,66,77,88,99,111,100,45,],将小于100的和大于等于
#100的分别放到一个dict中{‘k1′:大于等于100,’ke’:小于100}
list = [11,22,33,44,55,66,77,88,99,111,100,45,]
list1 = []
list2 = []
for i in list:
if i < 100:
list1.append(i)
else:
list2.append(i)
test_dict = {}
test_dict[‘k1’] = list1
test_dict[‘k2’] = list2
print(test_dict)
# {‘k1’: [11, 22, 33, 44, 55, 66, 77, 88, 99, 45], ‘k2’: [111, 100]}
#方法2
list = [11,22,33,44,55,66,77,88,99,111,100,45,]
test_dict = {}
for i in list:
if i >= 100:
if ‘k1’ in test_dict.keys():
test_dict[‘k1’].append(i)
else:
test_dict[‘k1’] = [i,]
else:
if ‘k2’ in test_dict.keys():
test_dict[‘k2’].append(i)
else:
test_dict[‘k2’] = [i,]
print(test_dict)
# {‘k2’: [11, 22, 33, 44, 55, 66, 77, 88, 99, 45], ‘k1’: [111, 100]}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/20915.html