Python - Filter odd elements from a dictionary's list of values

PHPz
Release: 2023-09-01 10:57:03
forward
1422 people have browsed it

Python - 从字典的值列表中筛选奇数元素

A dictionary is a popular data type in Python that has a key-value pair and does not allow duplicates. For filtering odd elements it has some inbuilt functions like items(), filter(), lambda and list() will be used to filter odd elements from list of values ​​in dictionary. The odd elements in the list are those that are not divisible by 2.

For example -

Given list, [10, 22, 21, 19, 2, 5]

After filtering odd elements from the list:

The final result becomes [10, 22, 2] (these are elements divisible by the integer 2).

grammar

The following syntax is used in the example -

items()
Copy after login

This is a built-in method that can be used to return a view object. The object consists of keys with value pairs.

filter()
Copy after login

Python's filter() element is used to filter elements based on specific conditions.

lambda
Copy after login

Functions lambda Provides a shortcut for declaring short anonymous functions using the lambda keyword. Lambda functions work when declared using the def keyword.

list()
Copy after login

list() is a Python built-in that creates list objects, it accepts an iterable construct and converts it to a list.

x % 2 != 0
or
x % 2 == 1
Copy after login

Both of the above representations illustrate the logic of filtering odd elements from a list of values.

Use dictionary comprehension and list comprehension through if-else statements

This program uses dictionary comprehension to convert the original dictionary into a new dictionary by filtering odd elements. This strange element can be filtered by using list compression with if-else statements.

Example

In the following example, the program is started using a function named odd_element, which accepts a parameter named dictionary. The same parameters are used with comprehension techniques, i.e. list and dictionary and if-statement to set a filter dictionary for odd elements in a list of values. Then create the dictionary's list of values ​​and store them in a variable name called dictionary. Next, call the function using and pass the parameter names as a dictionary containing key-value pairs and store them in the variable filter_dict. Finally, we print the result with the help of variable filter_dict.

def odd_elements(dictionary):
   return {key: [x for x in value if x % 2 != 0] for key, value in dictionary.items()}

# Create the dictionary
dictionary = {'A': [2, 4, 16, 19, 17], 'B': [61, 71, 90, 80, 10], 'C': [11, 121, 13, 14, 15]}
filter_dict = odd_elements(dictionary)
print("Filter odd elements from the value lists in dictionary:\n", filter_dict)
Copy after login

Output

Filter odd elements from the value lists in dictionary:
{'A': [19, 17], 'B': [61, 71], 'C': [11, 121, 13, 15]}
Copy after login

Using for loops and Filter() with Lambda functions

This program uses a for loop that will iterate over the keys and values ​​of dictionary items using the built-in method items(). It will then remove odd elements from the dictionary list using nested built-in functions such as list(), filter() and lambda.

Example

In the following example, we will use a for loop to iterate over a dictionary of variables containing keys with a list of values. To filter odd elements it will use three nested inbuilt functions namely list(), filter() and lambda() [This function sets the condition as x%2 != 0 and it will check if the given list of values is whether the integer is divisible by 2] and stores it in the variable filtered_dictionary. After filtering odd elements, set the value of filtered_dictionary in filtered_dictionary. Then create a dictionary consisting of a list of keys and values ​​and store it in a variable dictionary. Now this variable is set in the argument of the calling function odd_element() and stored in the variable filter_dict().

def odd_elements(dictionary):
   filtered_dictionary = {}
# for loop
   for key, value in dictionary.items():
# Using filter() with lambda
      filtered_values = list(filter(lambda x: x % 2 != 0, value))
      filtered_dictionary[key] = filtered_values
   return filtered_dictionary
# create the dictionary
dictionary = {'A': [1, 2, 3, 4, 5], 'B': [6, 7, 8, 9, 10], 'C': [11, 12, 13, 14, 15], 'D': [16, 17, 18, 19, 20]}
filter_dict = odd_elements(dictionary)
print("Filter odd elements from the value lists in dictionary:\n", filter_dict)
Copy after login

Output

Filter odd elements from the value lists in dictionary:
 {'A': [1, 3, 5], 'B': [7, 9], 'C': [11, 13, 15], 'D': [17, 19]}
Copy after login

Using for loops and list comprehension

The program uses a for loop using the built-in method items() to iterate over the dictionary and keys, then it will use a for loop and an if statement in a single line that represents a list comprehension.

Example

In the following example, you start the program by defining a function named filter_odd_elements(), which accepts a parameter named dictionary to access its value. Next, create an empty dictionary in the variable filter_dictionary and later store the new dictionary as the result. It will then use a for loop to iterate over each list of values ​​of the dictionary. Continue with the list comprehension using for and if statements and store it in the variable filter_values. Swap the same variables in filter_dictionary[key]. Then return the filter_dictionary whose filtered result does not contain odd elements. Create a dictionary containing a list of values ​​and store it in the variable dict. A new variable named f_dictionary stores the recursive function passed an argument named dict. Finally, use the print function that accepts the variable f_dictionary to get the result.

def filter_odd_elements(dictionary):
   filter_dictionary = {}
   for key, value in dictionary.items():
# List Comprehension
      filter_values = [x for x in value if x % 2 != 0]
      filter_dictionary[key] = filter_values
   return filter_dictionary
# Creation of dictionary
dict = {'A': [307, 907], 'B': [100, 200], 'C': [110, 120]}
# use the calling function
f_dictionary = filter_odd_elements(dict)
print("Filtration of odd elements from dictionary value list:\n", f_dictionary)
Copy after login

Output

Filtration of odd elements from dictionary value list:
 {'A': [307, 907], 'B': [], 'C': []}
Copy after login

Using dictionary comprehensions and Filter() with Lambda functions

This program uses dictionary comprehension to help convert a dictionary into a new form of dictionary. The filter() method uses the lambda function to eliminate odd elements from the dictionary's list of values.

Example

In the example below, we will show how dictionary comprehension uses three methods to set up logic based on filtering odd elements in a list of values, and uses a for loop to iterate over each key and value of the dictionary.

def odd_elements(dictionary):
   return {key: list(filter(lambda x: x % 2 == 1, value)) for key, value in dictionary.items()}

# Create the dictionary
dict_1 = {'I': [1, 2, 3, 4, 5], 'II': [6, 7, 8, 9, 10], 'III': [11, 12, 13, 14, 15]}
filter_dict = odd_elements(dict_1)
print("ODD NUMBER FILTRATION IN DICTIONARY VALUES:\n", filter_dict)
Copy after login

Output

ODD NUMBER FILTRATION IN DICTIONARY VALUES:
 {'I': [1, 3, 5], 'II': [7, 9], 'III': [11, 13, 15]}
Copy after login

Use dictionary comprehension and list comprehension

The program uses recursive functions to return comprehension techniques by using the return statement.

Example

In the following example, we will use a recursive function in the program to filter out the odd elements from the values ​​of the dictionary and return a new dictionary with the same keys and filtered values.

def odd_elements(dictionary):
   return {key: [x for x in value if x % 2 == 1] for key, value in dictionary.items()}
# create the dictionary and store the value by odd and even in the list
dictionary = {'list1': [100, 200, 300, 499, 599], 'list2': [699, 799, 899, 900, 1000]}
filter_dict = odd_elements(dictionary)
print("ODD NUMBER FILTRATION IN DICTIONARY VALUES:\n", filter_dict)
Copy after login

输出

ODD NUMBER FILTRATION IN DICTIONARY VALUES:
 {'list1': [499, 599], 'list2': [699, 799, 899]}
Copy after login

结论

我们讨论了基于从字典中的值列表中过滤奇数元素来解决此问题陈述的各种方法。上述所有示例大多使用综合技术,通过使用某种方法、循环或条件语句在 1-2 行内解决问题。当我们想要通过分配特定条件来过滤数据时,通常会使用程序目的。

The above is the detailed content of Python - Filter odd elements from a dictionary's list of values. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!