Python - фильтрация словарей по значениям в K-ом ключе в списке

Опубликовано: 12 Апреля, 2022

Имея список словарей, задача состоит в том, чтобы написать программу Python для фильтрации словарей на основе элементов K-го ключа в списке.

Примеры:

Input : test_list = [{“Gfg” : 3, “is” : 5, “best” : 10},

                           {“Gfg” : 5, “is” : 1, “best” : 1},

                           {“Gfg” : 8, “is” : 3, “best” : 9},

                           {“Gfg” : 9, “is” : 9, “best” : 8},

                           {“Gfg” : 4, “is” : 10, “best” : 7}], K = “best”, search_list = [1, 9, 8, 4, 5]

Output : [{‘Gfg’: 5, ‘is’: 1, ‘best’: 1}, {‘Gfg’: 8, ‘is’: 3, ‘best’: 9}, {‘Gfg’: 9, ‘is’: 9, ‘best’: 8}]

Explanation : Dictionaries with “best” as key and values other than 1, 9, 8, 4, 5 are omitted.

Input : test_list = [{“Gfg” : 3, “is” : 5, “best” : 10},

                           {“Gfg” : 5, “is” : 1, “best” : 1},

                           {“Gfg” : 8, “is” : 3, “best” : 9}], K = “best”, search_list = [1, 9, 4, 5]

Output : [{‘Gfg’: 5, ‘is’: 1, ‘best’: 1}, {‘Gfg’: 8, ‘is’: 3, ‘best’: 9}]



Explanation : Dictionaries with “best” as key and values other than 1, 9, 4, 5 are omitted.

Метод # 1: использование цикла + условных операторов

In this, key-value pairs are added to the resultant dictionary after checking for Kth keys values in the list using conditionals, iterated using a loop.

Python3

# Python3 code to demonstrate working of
# Filter dictionaries by values in Kth Key in list
# Using loop + conditional statements
  
# initializing list
test_list = [{"Gfg": 3, "is": 5, "best": 10},
             {"Gfg": 5, "is": 1, "best": 1},
             {"Gfg": 8, "is": 3, "best": 9},
             {"Gfg": 9, "is": 9, "best": 8},
             {"Gfg": 4, "is": 10, "best": 7}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing search_list
search_list = [1, 9, 8, 4, 5]
  
# initializing K
K = "best"
  
res = []
for sub in test_list:
  
    # checking if Kth key"s value present in search_list
    if sub[K] in search_list:
        res.append(sub)
  
# printing result
print("Filtered dictionaries : " + str(res))

Выход:

The original list is : [{‘Gfg’: 3, ‘is’: 5, ‘best’: 10}, {‘Gfg’: 5, ‘is’: 1, ‘best’: 1}, {‘Gfg’: 8, ‘is’: 3, ‘best’: 9}, {‘Gfg’: 9, ‘is’: 9, ‘best’: 8}, {‘Gfg’: 4, ‘is’: 10, ‘best’: 7}]

Filtered dictionaries : [{‘Gfg’: 5, ‘is’: 1, ‘best’: 1}, {‘Gfg’: 8, ‘is’: 3, ‘best’: 9}, {‘Gfg’: 9, ‘is’: 9, ‘best’: 8}]

Метод # 2: использование понимания списка

Similar to the above method, list comprehension is used to provide shorthand to the method used above.

Python3

# Python3 code to demonstrate working of
# Filter dictionaries by values in Kth Key in list
# Using list comprehension
  
# initializing list
test_list = [{"Gfg": 3, "is": 5, "best": 10},
             {"Gfg": 5, "is": 1, "best": 1},
             {"Gfg": 8, "is": 3, "best": 9},
             {"Gfg": 9, "is": 9, "best": 8},
             {"Gfg": 4, "is": 10, "best": 7}, ]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing search_list
search_list = [1, 9, 8, 4, 5]
  
# initializing K
K = "best"
  
# list comprehension as shorthand for solving problem
res = [sub for sub in test_list if sub[K] in search_list]
  
# printing result
print("Filtered dictionaries : " + str(res))

Выход:

The original list is : [{‘Gfg’: 3, ‘is’: 5, ‘best’: 10}, {‘Gfg’: 5, ‘is’: 1, ‘best’: 1}, {‘Gfg’: 8, ‘is’: 3, ‘best’: 9}, {‘Gfg’: 9, ‘is’: 9, ‘best’: 8}, {‘Gfg’: 4, ‘is’: 10, ‘best’: 7}]

Filtered dictionaries : [{‘Gfg’: 5, ‘is’: 1, ‘best’: 1}, {‘Gfg’: 8, ‘is’: 3, ‘best’: 9}, {‘Gfg’: 9, ‘is’: 9, ‘best’: 8}]

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.