Hướng dẫn python3 iterate over enum

Last update on August 19 2022 21:50:47 (UTC/GMT +8 hours)

Python Data Structure: Exercise-2 with Solution

Write a Python program to iterate over an enum class and display individual member and their value.

Nội dung chính

  • Python Data Structure: Exercise-2 with Solution
  • Python: Tips of the Day
  • Can you iterate through enum?
  • Is enum iterable Python?
  • How do you use an enum in a for loop in Python?
  • Can enum have multiple values Python?

Sample Solution:-

Python Code:

from enum import Enum
class Country(Enum):
    Afghanistan = 93
    Albania = 355
    Algeria = 213
    Andorra = 376
    Angola = 244
    Antarctica = 672
for data in Country:
    print('{:15} = {}'.format(data.name, data.value))
	

Sample Output:

Afghanistan     = 93                                                                                          
Albania         = 355                                                                                         
Algeria         = 213                                                                                         
Andorra         = 376                                                                                         
Angola          = 244                                                                                         
Antarctica      = 672  

Flowchart:

Hướng dẫn python3 iterate over enum

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to create an Enum object and display a member name and value.
Next: Write a Python program to display all the member name of an enum class ordered by their values.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Python: Tips of the Day

Checking whether all elements in the sequence are Truthful:

>>> all(a % 2==0 for a in range(0,10,2))
True


  • Exercises: Weekly Top 16 Most Popular Topics
  • SQL Exercises, Practice, Solution - JOINS
  • SQL Exercises, Practice, Solution - SUBQUERIES
  • JavaScript basic - Exercises, Practice, Solution
  • Java Array: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : Conditional Statement
  • HR Database - SORT FILTER: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : String
  • Python Data Types: Dictionary - Exercises, Practice, Solution
  • Python Programming Puzzles - Exercises, Practice, Solution
  • C++ Array: Exercises, Practice, Solution
  • JavaScript conditional statements and loops - Exercises, Practice, Solution
  • C# Sharp Basic Algorithm: Exercises, Practice, Solution
  • Python Lambda - Exercises, Practice, Solution
  • Python Pandas DataFrame: Exercises, Practice, Solution
  • Conversion Tools
  • JavaScript: HTML Form Validation


I'm using the backported Enum functionality from python 3.4 with python 2.7:

> python --version
Python 2.7.6
> pip install enum34
# Installs version 1.0...

According to the documentation for Enums in python 3 (https://docs.python.org/3/library/enum.html#creating-an-enum), "Enumerations support iteration, in definition order". However, iteration is not happening in order for me:

>>> from enum import Enum
>>> class Shake(Enum):
...     vanilla = 7
...     chocolate = 4
...     cookies = 9
...     mint = 3
...     
>>> for s in Shake:
...     print(s)
...     
Shake.mint
Shake.chocolate
Shake.vanilla
Shake.cookies

Am I misunderstanding something, or is iteration in definition order just not supported in the backported versions of Enums yet? Assuming the latter, is there an easy way to force it to happen in order?

asked Sep 22, 2014 at 19:58

I found the answer here: https://pypi.python.org/pypi/enum34/1.0.

For python <3.0, you need to specify an __order__ attribute:

>>> from enum import Enum
>>> class Shake(Enum):
...     __order__ = 'vanilla chocolate cookies mint'
...     vanilla = 7
...     chocolate = 4
...     cookies = 9
...     mint = 3
...     
>>> for s in Shake:
...     print(s)
...     
Shake.vanilla
Shake.chocolate
Shake.cookies
Shake.mint

answered Sep 22, 2014 at 20:01

TroyTroy

20.6k20 gold badges71 silver badges101 bronze badges

3

use

__order__ 

to define the order of enums for python version less than 3 . It is not necessary in python3 but make sure the order which is supplied same as declared order otherwise it will give error:

TypeError: member order does not match _order_


import enum


class EXCHANGE(enum.Enum):
    __order__ = " EXCHANGE_NSE EXCHANGE_BSE EXCHANGE_NFO EXCHANGE_CDS EXCHANGE_BFO EXCHANGE_MCX EXCHANGE_BCD "
    EXCHANGE_NSE = "NSE"
    EXCHANGE_BSE = "BSE"
    EXCHANGE_NFO = "NFO"
    EXCHANGE_CDS = "CDS"
    EXCHANGE_BFO = "BFO"
    EXCHANGE_MCX = "MCX"
    EXCHANGE_BCD = "BCD"


if __name__ == "__main__":
    for ex in EXCHANGE:
        print(f"{ex.name} : {ex.value}")

Output:

EXCHANGE_NSE : NSE
EXCHANGE_BSE : BSE
EXCHANGE_NFO : NFO
EXCHANGE_CDS : CDS
EXCHANGE_BFO : BFO
EXCHANGE_MCX : MCX
EXCHANGE_BCD : BCD

answered Feb 10 at 6:54

devpdevp

2,0242 gold badges13 silver badges23 bronze badges

Can you iterate through enum?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

Is enum iterable Python?

Example 3: Enumerations are iterable. They can be iterated using loops. In this example, we will use for loop to print all the members of the Enum class.

How do you use an enum in a for loop in Python?

Enumerate() in Python This enumerated object can then be used directly for loops or converted into a list of tuples using the list() method. Parameters: Iterable: any object that supports iteration. Start: the index value from which the counter is to be started, by default it is 0.

Can enum have multiple values Python?

Enums can't have multiple value per name.