【python ---字典练习】索引 增删改 嵌套
# 作业
#写代码:有如下字典
# 按照要求实现每一个功能
# dict = {"k1":"v1","k2":"v2","k3":"v3"}
# 1、请循环遍历出所有的key
dic = {"k1":"v1","k2":"v2","k3":"v3"}
re = dic.keys()
for i in re:
print(i,end=' ')
# # 2, 请循环遍历出所有的value
dic = {"k1":"v1","k2":"v2","k3":"v3"}
re = dic.values()
for i in re:
print(i,end=' ')
# 3、请循环遍历出所有的key和value
dic = {"k1":"v1","k2":"v2","k3":"v3"}
re = dic.items()
for k,v in re:
print(k,v,end=' ')
# 4、请在字典中增加一个键值对,"k4":"v4",输出添加后的字典
dic = {"k1":"v1","k2":"v2","k3":"v3"}
dic['k4'] = 'v4'
print(dic)
# 5、请删除字典中键值对"k1":"v1",并输出删除后的结果
dic = {"k1":"v1","k2":"v2","k3":"v3"}
dic.pop('k1')
print(dic)
# 6、请删除字典中键"k5"对应的键值对,如果字典中不存在键"k5",则不报错,返回None
dic = {"k1":"v1","k2":"v2","k3":"v3"}
re = dic.pop('k5',None)
print(re)
# 7、请获取字典中"k2"对应的值
dic = {"k1":"v1","k2":"v2","k3":"v3"}
print(dic['k2'])
# 8、请获取字典中"k6"对应的值,如果不存在,则不报错,并且让其返回None。
dic = {"k1":"v1","k2":"v2","k3":"v3"}
re = dic.pop('k6',None)
print(re)
# 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"}
dict2.update(dic)
print(dict2)
# 10.现有一个列表li = [1,2,3,'a',4,'c'],
# 有一个字典(此字典是动态生成的,你并不知道他里面有多少键值对,所以用dic={}模拟字典;
# 现在需要完成这样的操作:如果该字典没有"k1"这个键,那就创建
# 这个"k1"键和对应的值(该键对应的值为空列表),并将列表li中的索引位为奇数对应的元素,
# 添加到"k1"这个键对应的空列表中。如果该字典中有"k1"这个键,且k1对应的value是列表类型。
# 那就将该列表li中的索引位为奇数对应的元素,添加到"k1",这个键对应的值中。
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. 获取汪峰的名字。
# 2.获取这个字典:{'name':'国际章','age':38}。
# 3. 获取汪峰妻子的名字。
# 4. 获取汪峰的第三个孩子名字。
# 1.
print(dic['name'])
# 2
print(dic['wife'])
# 3
print(dic['wife'][0]['name'])
# 4
print(dic['children']['girl_three'])
#