Python - 字典練習



字典練習 1

Python 程式,透過從給定字典中提取鍵來建立一個新字典。

d1 = {"one":11, "two":22, "three":33, "four":44, "five":55}
keys = ['two', 'five']
d2={}
for k in keys:
   d2[k]=d1[k]
print (d2)

它將產生以下輸出 -

{'two': 22, 'five': 55}

字典練習 2

Python 程式,將字典轉換為(k,v)元組列表

d1 = {"one":11, "two":22, "three":33, "four":44, "five":55}
L1 = list(d1.items())
print (L1)

它將產生以下輸出 -

[('one', 11), ('two', 22), ('three', 33), ('four', 44), ('five', 55)]

字典練習 3

Python 程式,刪除字典中具有相同值的鍵。

d1 = {"one":"eleven", "2":2, "three":3, "11":"eleven", "four":44, "two":2}
vals = list(d1.values())#all values
uvals = [v for v in vals if vals.count(v)==1]#unique values
d2 = {}
for k,v in d1.items():
   if v in uvals:
      d = {k:v}
      d2.update(d)
print ("dict with unique value:",d2)

它將產生以下輸出 -

dict with unique value: {'three': 3, 'four': 44}

字典練習程式

  • Python 程式,根據值對字典列表進行排序

  • Python 程式,從給定字典中提取每個鍵都具有非數字值的字典。

  • Python 程式,從兩個專案(k,v)元組的列表構建字典。

  • Python 程式,使用解包運算符合並兩個字典物件。

廣告