Python字典练习题

时间:2023-02-24 07:35:04

有字典 dic = {"k1": "v1", "k2": "v2", "k3": "v3"},实现以下功能:

  1、遍历字典 dic 中所有的key

  参考答案:

Python字典练习题Python字典练习题
#!-*- coding:utf-8 -*-

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

for k in dic.keys():
    print(k)
View Code

  

  2、遍历字典 dic 中所有的value

  参考答案:

Python字典练习题Python字典练习题
#!-*- coding:utf-8 -*-

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

for v in dic.values():
    print(v)
View Code

  

  3、循环遍历字典 dic 中所有的key和value

  参考答案:

Python字典练习题Python字典练习题
#!-*- coding:utf-8 -*-

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

for k,v in dic.items():
    print(k,v)
View Code

  

  4、添加一个键值对"k4","v4",输出添加后的字典 dic

  参考答案:

Python字典练习题Python字典练习题
#!-*- coding:utf-8 -*-

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

dic["k4"] = "v4"
print(dic)
View Code

  

  5、删除字典 dic 中的键值对"k1","v1",并输出删除后的字典 dic

  参考答案:

Python字典练习题Python字典练习题
#!-*- coding:utf-8 -*-

dic = {"k1": "v1", "k2": "v2", "k3": "v3"}
dic["k4"] = "v4"

dic.pop("k1")  # 方法1:可以返回删除的k对应的value,不存在则会引发异常
del dic['k1'] # 方法2:不返回删除的k对应的value,不存在则会引发异常
print(dic) # {'k2': 'v2', 'k3': 'v3', 'k4': 'v4'}
View Code

  

  6、删除字典 dic 中 'k5' 对应的值,若不存在,使其不报错,并返回None

  参考答案:

Python字典练习题Python字典练习题
#!-*- coding:utf-8 -*-
dic = {"k1": "v1", "k2": "v2", "k3": "v3"}

dic["k4"] = "v4"
dic.pop("k1")

print(dic.pop("k5",None)) # None
View Code

  

  7、获取字典 dic 中“k2”对应的值

  参考答案:

Python字典练习题Python字典练习题
#!-*- coding:utf-8 -*-
dic = {"k1": "v1", "k2": "v2", "k3": "v3"}

dic["k4"] = "v4"
dic.pop("k1") 
print(dic.pop("k5",None)) 

print(dic["k2"])  # v2 方法1:不存在时,会报错
print(dic.get("k2")) # v2 方法2:不存在时,返回 None
View Code

  

  8、获取字典 dic 中"k6"对应的值,如果不存在,使其不报错,并且让其返回数据 None

  参考答案:

Python字典练习题Python字典练习题
#!-*- coding:utf-8 -*-
dic = {"k1": "v1", "k2": "v2", "k3": "v3"}

dic["k4"] = "v4"
dic.pop("k1") 
print(dic.pop("k5",None)) 

print(dic.get("k6"))  # None
View Code

  

  9、有字典 dic2 = {'k1':"v111",'a':"b"} 通过一行操作使 dic2 = {'k1':"v111",'k2':"v2",'k3':"v3",'k4': 'v4','a':"b"}

  参考答案:

Python字典练习题Python字典练习题
#!-*- coding:utf-8 -*-
dic = {"k1": "v1", "k2": "v2", "k3": "v3"}

dic["k4"] = "v4"
dic.pop("k1") 
print(dic.pop("k5",None)) 

print(dic)  # {'k2': 'v2', 'k3': 'v3', 'k4': 'v4'}  打印此时的字典 dic
dic2 = {'k1': "v111", 'a': "b"}
dic2.update(dic)  # 将字典dic2的键值对添加到字典dic中
print(dic2)  # {'k1': 'v111', 'a': 'b', 'k2': 'v2', 'k3': 'v3', 'k4': 'v4'}
View Code

  

  10、组合嵌套,实现功能,现有列表如下:

    list = [['k', ['qwe', 20, {'k1': ['tt', 3, '1']}, 89], 'ab']]

  (1)将列表中的‘tt’变成大写(两种方式)

  参考答案:

Python字典练习题Python字典练习题
#!-*- coding:utf-8 -*-

list = [['k', ['qwe', 20, {'k1': ['tt', 3, '1']}, 89], 'ab']]
print(list[0][1][2].get('k1')[0].upper())  # TT   方法1--upper()返回大写字符串
print(list[0][1][2].get('k1')[0].swapcase())  # TT 方法2--swapcase() 大小写互换
View Code

  (2)将数字 3 变成字符串 ‘100’(两种方式)

  参考答案:

Python字典练习题Python字典练习题
#!-*- coding:utf-8 -*-

list = [['k', ['qwe', 20, {'k1': ['tt', 3, '1']}, 89], 'ab']]

list[0][1][2].get('k1')[1] = '100'
list[0][1][2]['k1'][1] = '100'
print(list)
View Code

  (3)将列表中的字符串‘1’变成数字101(两种方式)

  参考答案:

Python字典练习题Python字典练习题
#!-*- coding:utf-8 -*-

list = [['k', ['qwe', 20, {'k1': ['tt', 3, '1']}, 89], 'ab']]

list[0][1][2]['k1'][-1] = 101 # 方法1
list[0][1][2].get('k1')[2] = 101 # 方法2
print(list[0][1][2].get('k1'))
View Code

  

  11、按照要求实现以下功能:li = [1,2,3,'a','b',4,'c'],有一个字典(此字典是动态生成的,你并不知道它有多少键值对,所以用 dic={} 模拟),具体操作如下:如果字典没有'k1'这个键,那就创建这个'k1'键和对应的值(对应值设为空列表),并将列表li中的索引为奇数对应的元素,添加到'k1'这个键对应的空列表中;如果有'k1'这个键,且'k1'对应的value值是列表类型,那就将列表li中的索引为奇数对应的元素,添加到'k1'这个键对应的值中。

  参考答案:

Python字典练习题Python字典练习题
#!-*- coding:utf-8 -*-

li = [1,2,3,'a','b',4,'c']
dic = {} # 动态生成
if len(dic.keys()) > 0: 
    ''' 判断字典是否为空 '''
    for i in dic.keys():
        ''' 遍历字典的 key '''
        if 'k1' in i and type(dic.get('k1')==list):
            ''' 判断 "k1"是否存在字典中且对应的键值是否是一个列表 '''
            for index,k in enumerate(li):
                ''' 遍历列表中的索引和索引对应的列表元素 '''
                if index%2 == 1:
                    ''' 判断索引是否为奇数 '''
                    dic['k1'].append(li[index])
else:
    print(len(dic)) #验证
    dic['k1'] = []
    for index,k in enumerate(li):
        if index%2 == 1:
            dic['k1'].append(li[index])

print(dic)
View Code