Python --dict笔记以及 练习

# 1:通过默认赋值
dic = {}

# 2:通过赋值直接创建
dic = {'spam':1,'egg':2,'bar':3}
dic = dict(one=1,two=2,three=3)

# 3:通过dict函数和关键字参数
dict(name='喵哥',age=19)

# 4:通过列表转字典
l = [('spam',1) , ('egg',2) , ('bar',3)]
dic = dict(l)

# 5:通过zip创建 拉链函数
re = zip([1,2,3,4],[11,22,33,44])
dic = dict(zip('abc',[11,22,33,44]))
print(dic)

# 6:通过推导式创建
dic = {str(i) : i*2 for i in range(9)}
print(dic)

# 7:通过dict.fromkeys()创建,
# 通常用来初始化字典,设置value的默认值
dic = dict.fromkeys('nihao',3)
print(dic)

# 8:其他方式
l = ['x', 1, 'y', 2, 'z', 3]
# l[::2]
# l[1::2]
# dict(zip(['x','y','z'],[1,2,3]))
dic = dict(zip(l[::2], l[1::2]))
print(dic)

#使用while循环 模仿For 循环迭代可迭代对象
# 可迭代对象 iterable
# 迭代器 iterator
# 生成器 generator
re = range(9).__iter__()

# l1 = [1, 2, 3, 4, 5]
# obj = l1.__iter__()
# i =0
# while i<len(l1):
# print(obj.__next__())
# i+=1
#
#
# re = (i for i in range(9))
# for i in re:
# print(i)

dic={'n':'nihao','i':1,'h':1.1,'a':False,'o':True,'t':1.1}
dic1={1:1,1.1:1,True:1,False:1}
# print('key --',dic.keys())
# print('value -- ',dic.values()


try:
print(dic['asdfsdf'])
except Exception:
print('未找到')


d = {'a': 1, 'b': 2, 'c': 3}
# 迭代 k 键
# for key in d:
# print(key)
# 迭代 value 值
# for value in d.values():
# print(value)

#如果要同时迭代key和value,可以用for k, v in d.items()
# for k, v in d.items():
# if k == 'c' :
# print(k, ':', v)


#--------------------------------------------------------------------------------------------------------

#字典的操作
dic = {'name':'景文','age':17}

#---------------------------------------- 增


# dic['gender'] = 'man' #没有K就增加这个K
# dic['name'] = 'jwbs' #如果有这个K就把这个K的value改了
# re = dic.setdefault('name1','jwbs') #re = jwbs 'name1'如果dic里面没有这个K,就添加,否则,不会增加这个K也不会改变value
#print(dic)


#---------------------------------------- 删
dic = {'name':'景文','age':17}
# re = dic.pop('name') #传个K返回V 然后删除K,V re = 景文
# dic.popitem() #删除最后的k,v
# dic.clear() #清空字典里面的元素
# del(dic) #删除整个字典
print(dic)


#---------------------------------------- 改

dic = {'name':'景文','age':17}
dic1 = {'n':'jw','a':19}

# dic['name'] = 'jwbs' #如果有这个K就把这个K的value改了
# dic.update([('age',199)])
# dic.update(dic1) #如果没有这个键,就插入进去,有的话就修改
# dic1.update(a='nihao',b=200)
print(dic1)

#---------------------------------------- 查
dic = {'name':'景文','age':17}
print(dic['name']) #输入K 查value
# print(dic('adasd')) #找不到这个K 会报错
re = dic.get('name') #通过get函数获取 value
print(dic.keys()) #通过keys函数获取所有K
print(dic.values()) #通过values函数获取所有values
print(dic.items()) #通过items函数获取所有K,V



#---------------------------------------- 字典基操

dic = {"k1":"v1","k2":"v2","k3":"v3"}

#1、请循环遍历出所有的key
# for k in dic:
# print(k)
#2, 请循环遍历出所有的value
# for v in dic.values():
# print(v)
#3、请循环遍历出所有的key和value
# for k,v in dic.items():
# print(k,'---',v)
#4、请在字典中增加一个键值对,"k4":"v4",输出添加后的字典
dic = {"k1":"v1","k2":"v2","k3":"v3"}
dic['kv'] = 'v4'
print(dic)
#5、请删除字典中键值对"k1":"v1",并输出删除后的结果
dic.pop('k1')
print(dic)
#6、请删除字典中键"k5"对应的键值对,如果字典中不存在键"k5",则不报错,返回None
print(dic.pop('k5', '你要删除的不存在'))
#7、请获取字典中"k2"对应的值
print(dic.get('k2'))
#8、请获取字典中"k6"对应的值,如果不存在,则不报错,并且让其返回None。
print(dic.get('k6'),'None')
#9、现有dict2 = {"k1":"v11","a":"b"},通过一行操作使dict2 = {"k1":"v1","k2":"v2","k3":"v3","a":"b"}
dict2 = {"k1":"v11","a":"b"}
dic = {"k1":"v1","k2":"v2","k3":"v3","a":"b"}

dict2.update(dic)
print(dict2)




dic = {}
li = [1,2,3,'a',4,'c']
if "k1" not in dic:
dic.setdefault("k1", [])
for i in li:
if li.index(i) % 2 == 1:
dic["k1"].append(i)
else:
if type(dic["k1"]) == type([]):
for i in li:
if li.index(i) % 2 == 1:
dic["k1"].append(i)
else:
print("字典K1,VALUE不是列表,无法追加")
print('============------------------',dic)


# 12现在有如下字典,完成一下需求:
dic = {
'name':'汪峰',
'age':48,
'wife':[{'name':'国际章','age':38}],
'children':{'girl_first':'小苹果','girl_second':'小怡','girl_three':'顶顶'}
}
# 1. 获取汪峰的名字。
print(dic.get('name'))
# 2.获取这个字典:{'name':'国际章','age':38}。
print(dic.get('wife')[0])
# 3. 获取汪峰妻子的名字。
print('----',dic.get('wife')[0].get('name'))
# 4. 获取汪峰的第三个孩子名字。
print('----',dic.get('children').get('girl_three'))











posted @ 2020-07-17 16:44  Ric_A  阅读(179)  评论(0编辑  收藏  举报