📜  Python|从字典中提取特定键

📅  最后修改于: 2022-05-13 01:54:57.990000             🧑  作者: Mango

Python|从字典中提取特定键

我们在Python中有很多字典容器的变体和应用,有时,我们希望对字典中的键进行过滤,即仅提取特定容器中存在的键。让我们讨论可以执行此操作的某些方式。方法#1:使用字典理解+items()这个问题可以通过使用通过items函数提取的希望被过滤的键进行重建来执行,并且字典函数可以生成所需的字典。

Python3
# Python3 code to demonstrate
# Extracting specific keys from dictionary
# Using dictionary comprehension + items()
 
# initializing dictionary
test_dict = {'nikhil' : 1, "akash" : 2, 'akshat' : 3, 'manjeet' : 4}
 
# printing original list
print("The original dictionary : " + str(test_dict))
 
# Using dictionary comprehension + items()
# Extracting specific keys from dictionary
res = {key: test_dict[key] for key in test_dict.keys()
                               & {'akshat', 'nikhil'}}
 
# print result
print("The filtered dictionary is : " + str(res))


Python3
# Python3 code to demonstrate
# Extracting specific keys from dictionary
# Using dict()
 
# initializing dictionary
test_dict = {'nikhil' : 1, "akash" : 2, 'akshat' : 3, 'manjeet' : 4}
 
# printing original list
print("The original dictionary : " + str(test_dict))
 
# Using dict()
# Extracting specific keys from dictionary
res = dict((k, test_dict[k]) for k in ['nikhil', 'akshat']
                                        if k in test_dict)
 
# print result
print("The filtered dictionary is : " + str(res))


C++
#include 
using namespace std;
 
int main() {
 
    cout<<"GFG!";
    return 0;
}


输出 :
The original dictionary : {'manjeet': 4, 'akshat': 3, 'akash': 2, 'nikhil': 1}
The filtered dictionary is : {'akshat': 3, 'nikhil': 1}

方法 #2:使用 dict() dict函数可用于通过将使用列表推导执行的逻辑转换为字典来执行此任务。

Python3

# Python3 code to demonstrate
# Extracting specific keys from dictionary
# Using dict()
 
# initializing dictionary
test_dict = {'nikhil' : 1, "akash" : 2, 'akshat' : 3, 'manjeet' : 4}
 
# printing original list
print("The original dictionary : " + str(test_dict))
 
# Using dict()
# Extracting specific keys from dictionary
res = dict((k, test_dict[k]) for k in ['nikhil', 'akshat']
                                        if k in test_dict)
 
# print result
print("The filtered dictionary is : " + str(res))

C++

#include 
using namespace std;
 
int main() {
 
    cout<<"GFG!";
    return 0;
}
输出 :
The original dictionary : {'manjeet': 4, 'akshat': 3, 'akash': 2, 'nikhil': 1}
The filtered dictionary is : {'akshat': 3, 'nikhil': 1}