search
HomeBackend DevelopmentPython TutorialPython - Filter odd elements from a dictionary's list of values

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()

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

filter()

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

lambda

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

list()

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

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)

Output

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

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)

Output

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

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)

Output

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

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)

Output

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

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)

输出

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

结论

我们讨论了基于从字典中的值列表中过滤奇数元素来解决此问题陈述的各种方法。上述所有示例大多使用综合技术,通过使用某种方法、循环或条件语句在 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!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor