Python – 提取 key 的值(如果 key 同時出現在列表和字典中)


如果需要同時從列表和字典中提取鍵的值,可以使用一個簡單的迭代和“all”運算子。

示例

以下對此進行了演示:

my_list = ["Python", "is", "fun", "to", "learn", "and", "teach", 'cool', 'object', 'oriented']

my_dictionary = {"Python" : 2, "fun" : 4, "learn" : 6}

K = "Python"
print("The value of K is ")
print(K)

print("The list is : " )
print(my_list)

print("The dictionary is : " )
print(my_dictionary)

my_result = None
if all(K in sub for sub in [my_dictionary, my_list]):
   my_result = my_dictionary[K]

print("The result is : ")
print(my_result)

輸出

The value of K is
Python
The list is :
['Python', 'is', 'fun', 'to', 'learn', 'and', 'teach']
The dictionary is :
{'Python': 2, 'fun': 4, 'learn': 6}
The result is :
2

說明

  • 定義一個字串列表並顯示在控制檯中。

  • 定義一個值字典並顯示在控制檯中。

  • 定義 K 的值並顯示在控制檯中。

  • 值為 None。

  • 使用“all”運算子和簡單迭代來檢查字典中的值是否出現在列表中。

  • 如果為“是”,則該值將被賦予字典中的“K”元素。

  • 此值將作為輸出顯示在控制檯中。

更新於: 13-9-2021

485 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告