Creating an iterator from a dictionary.
class DictIterator:
def __init__(self, data):
self.data = list(data.items())
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.data):
raise StopIteration
key, value = self.data[self.index]
self.index += 1
return f"{key}: {value}"
it = iter(DictIterator({"a": 1, "b": 2}))
print(list(it))
class DictIterator:
def __init__(self, data):
self.data = list(data.items())
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.data):
raise StopIteration
key, value = self.data[self.index]
self.index += 1
return f"{key}: {value}"
it = iter(DictIterator({"a": 1, "b": 2}))
print(list(it))
Author: SandhyaR | Tags: iterator | 1540 + Python FAQs | Report This Q. | Share This Q.
|
|
arithmetic-expression
|
indentation
|
logical-operator
|
virtual-environment
|
sum()
|
set
|
exception-handling
|
iterator
|
array
|
dictionary
|
conditional-statement
|
bitwise
|
statement
|
operand
|
list-comprehension
|
swapping
|
numeric
|
feature
|
pickling-&-unpickling
|
random
|
logical-operator
|
tuple
|
recurssion
|
escape-operator
|
datatype
|
precedence-and-associativity
|
string
|
recursion
|
method
|
parameter
|
encapsulation
|
inheritance
|
matplotlib
|
init
|
zip-function
|
oops
|
goto-function
|
range
|
python
|
mutable
|
error
|
control-statement
|
shallow-copy
|
keyword
|
library
|
pep
|
int
|
multiprocessing
|
function
|
generators-in-python
|
precedence
|
matrix
|
polymorphism
|
for
|
numpy
|
heap-memory
|
docstring
|
assert
|
complex
|
python-module
|
syntax
|
threading
|
constructor
|
sys
|
data-type
|
file
|
head-and-tail
|
comprehension
|
zfill-function
|
class
|
namespace
|
encoding
|
__init_subclass__
|
while-and-for-loop
|
installation
|
turtle
|
boolean
|
print
|
mapping-function
|
file-handling
|
condition
|
fabs-function
|
decorator
|
counter-function
|
inherit
|
deep-copy
|
list
|
module
|
enumerate()
|
exception
|
destructor
|
class-and-object
|
format
|
slice
|
logical-operation
|
odd-number
|
asyncio-module
|
generator
|
operator
|
regular-expression
|
counter
|
identifier
|
magic-method
|
built-in-function
|
matrix-list-comprehension
|
compute
|
pseudocode
|
lambda
|
random-function
|
multithreading
|
conversion
|
mysql
|
datetime
|
arithmetic-operation
|
pandas
|
thread
|
loop
|
debugging
|
__future__
|
math
|
indexing
|
gil
|
variable
|
return-statement
|
list-comprehension
|
expression