Python – 从其他键值中提取目标键
有时,在使用Python字典时,我们可能会遇到一个问题,即当存在完全匹配时,我们需要根据其他匹配的记录键来提取特定键。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环+条件
这是可以执行此任务的方式之一。在此,我们迭代字典键并检查每个键的匹配值。
# Python3 code to demonstrate working of
# Extract target key from other key values
# Using loop + condition
# initializing list
test_list = [{ 'name' : 'Manjeet', 'English' : 14, 'Maths' : 2},
{ 'name' : 'Akshat', 'English' : 7, 'Maths' : 13},
{ 'name' : 'Akash', 'English' : 1, 'Maths' : 17},
{ 'name' : 'Nikhil', 'English' : 10, 'Maths' : 18}]
# printing original list
print("The original list is : " + str(test_list))
# initializing filter items
filt_key = {'English' : 7, 'Maths' : 13}
# Extract target key from other key values
# Using loop + condition
res = []
for sub in test_list:
if sub["English"] == filt_key["English"] and sub["Maths"] == filt_key["Maths"]:
res.append(sub['name'])
# printing result
print("The filtered result : " + str(res))
The original list is : [{‘name’: ‘Manjeet’, ‘English’: 14, ‘Maths’: 2}, {‘name’: ‘Akshat’, ‘English’: 7, ‘Maths’: 13}, {‘name’: ‘Akash’, ‘English’: 1, ‘Maths’: 17}, {‘name’: ‘Nikhil’, ‘English’: 10, ‘Maths’: 18}]
The filtered result : [‘Akshat’]
方法#2:使用循环+条件(用于多个/未知键)
这以与上述方法类似的方式执行任务。使用这种方法的优点是不需要在条件下手动输入所有键。
# Python3 code to demonstrate working of
# Extract target key from other key values
# Using loop + conditions ( for multiple / unknown keys )
def hlper_func(test_keys, filt_key):
for key in test_keys.keys():
if key in filt_key:
if test_keys[key] != int(filt_key[key]):
return False
return True
# initializing list
test_list = [{ 'name' : 'Manjeet', 'English' : 14, 'Maths' : 2},
{ 'name' : 'Akshat', 'English' : 7, 'Maths' : 13},
{ 'name' : 'Akash', 'English' : 1, 'Maths' : 17},
{ 'name' : 'Nikhil', 'English' : 10, 'Maths' : 18}]
# printing original list
print("The original list is : " + str(test_list))
# initializing filter items
filt_key = {'English' : 7, 'Maths' : 13}
# Extract target key from other key values
# Using loop + conditions ( for multiple / unknown keys )
res = []
for sub in test_list:
if hlper_func(sub, filt_key):
res.append(sub['name'])
# printing result
print("The filtered result : " + str(res))
The original list is : [{‘name’: ‘Manjeet’, ‘English’: 14, ‘Maths’: 2}, {‘name’: ‘Akshat’, ‘English’: 7, ‘Maths’: 13}, {‘name’: ‘Akash’, ‘English’: 1, ‘Maths’: 17}, {‘name’: ‘Nikhil’, ‘English’: 10, ‘Maths’: 18}]
The filtered result : [‘Akshat’]