📜  Python – 提取嵌套值中特定键的值

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

Python – 提取嵌套值中特定键的值

给定一个以嵌套字典为值的字典,提取具有特定键的所有值。

方法 #1:使用列表理解 + items()

这是可以执行此任务的方式之一。在此,我们使用列表推导来执行提取特定键的任务,并且使用 items() 来获取所有 items()。

Python3
# Python3 code to demonstrate working of 
# Extract values of Particular Key in Nested Values
# Using list comprehension
  
# initializing dictionary
test_dict = {'Gfg' : {"a" : 7, "b" : 9, "c" : 12},
             'is' : {"a" : 15, "b" : 19, "c" : 20}, 
             'best' :{"a" : 5, "b" : 10, "c" : 2}}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing key
temp = "c"
  
# using item() to extract key value pair as whole
res = [val[temp] for key, val in test_dict.items() if temp in val]
  
# printing result 
print("The extracted values : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Extract values of Particular Key in Nested Values
# Using list comprehension + values() + keys() 
  
# initializing dictionary
test_dict = {'Gfg' : {"a" : 7, "b" : 9, "c" : 12},
             'is' : {"a" : 15, "b" : 19, "c" : 20}, 
             'best' :{"a" : 5, "b" : 10, "c" : 2}}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing key
temp = "c"
  
# using keys() and values() to extract values
res = [sub[temp] for sub in test_dict.values() if temp in sub.keys()]
  
# printing result 
print("The extracted values : " + str(res))


输出
The original dictionary is : {'Gfg': {'a': 7, 'b': 9, 'c': 12}, 'is': {'a': 15, 'b': 19, 'c': 20}, 'best': {'a': 5, 'b': 10, 'c': 2}}
The extracted values : [12, 20, 2]

方法 #2:使用列表理解 + values() + keys()

上述功能的组合可以用来解决这个问题。在此,我们使用 values() 和 keys() 分别获取值和键,而不是使用 items() 一次提取。

Python3

# Python3 code to demonstrate working of 
# Extract values of Particular Key in Nested Values
# Using list comprehension + values() + keys() 
  
# initializing dictionary
test_dict = {'Gfg' : {"a" : 7, "b" : 9, "c" : 12},
             'is' : {"a" : 15, "b" : 19, "c" : 20}, 
             'best' :{"a" : 5, "b" : 10, "c" : 2}}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing key
temp = "c"
  
# using keys() and values() to extract values
res = [sub[temp] for sub in test_dict.values() if temp in sub.keys()]
  
# printing result 
print("The extracted values : " + str(res)) 
输出
The original dictionary is : {'Gfg': {'a': 7, 'b': 9, 'c': 12}, 'is': {'a': 15, 'b': 19, 'c': 20}, 'best': {'a': 5, 'b': 10, 'c': 2}}
The extracted values : [12, 20, 2]