Python字典練習題


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

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

  參考答案:

#!-*- coding:utf-8 -*-

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

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

  

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

  參考答案:

#!-*- coding:utf-8 -*-

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

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

  

  3、循環遍歷字典 dic 中所有的key和value

  參考答案:

#!-*- 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

  參考答案:

#!-*- coding:utf-8 -*-

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

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

  

  5、刪除字典 dic 中的鍵值對"k1","v1",並輸出刪除后的字典 dic

  參考答案:

#!-*- 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

  參考答案:

#!-*- 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”對應的值

  參考答案:

#!-*- 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

  參考答案:

#!-*- 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"}

  參考答案:

#!-*- 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’變成大寫(兩種方式)

  參考答案:

#!-*- 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’(兩種方式)

  參考答案:

#!-*- 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(兩種方式)

  參考答案:

#!-*- 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'這個鍵對應的值中。

  參考答案:

#!-*- 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

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM