Table of Contents
grammar
Use dictionary comprehension and list comprehension through if-else statements
Example
Output
Using for loops and Filter() with Lambda functions
Using for loops and list comprehension
Using dictionary comprehensions and Filter() with Lambda functions
Use dictionary comprehension and list comprehension
输出
结论
Home Backend Development Python Tutorial Python - Filter odd elements from a dictionary's list of values

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

Sep 01, 2023 am 10:57 AM

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!

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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Learning Python: Is 2 Hours of Daily Study Sufficient? Learning Python: Is 2 Hours of Daily Study Sufficient? Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Which is part of the Python standard library: lists or arrays? Which is part of the Python standard library: lists or arrays? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python for Web Development: Key Applications Python for Web Development: Key Applications Apr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

See all articles