Level 1 : 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))

Author: SandhyaR | Tags: iterator | 1859+ Python FAQs | Share
thread-safe-data-structures-(queue.queue) | formatting-with-strftime | compute | counter-function | array | data-types | escape-operator | default-arguments | functional-programming | comprehension | encoding | encapsulation | data-type-conversions | function-argument | intering | descriptors | class-and-object | goto-function | data-structures | lambdas | range | loop-control-statements | defining-functions | numeric | methods | else-statement | operator | max-min | copy | logical-operator | slice | string | tuple | comment | library | touples | why-use-multiprocessing-over-threading?-(gil) | reading-and-writing-files | import-method | else | introduction-to-python | string-slicing | filter-function | factorial-function | counter | string-slicing | dictionary-comprehensions | identity-operators-(is,-is-not) | matrix-list-comprehension | def | dataframe-and-series-objects | function-and-scope | control-statement | file-handling | mutable | file-handling | variable | odd-number | sys-module | data-type | fabs-function | multiprocessing | tuples | print-statement | list-method | reading:-read(),-readline(),-readlines() | time-series-with-pandas | handling-missing-values-(fillna,-dropna) | list-slicing | context-manager | python-operators | collection | working-with-dates-and-times | generators | format | anchors-(^,-$) | multithreading | split | implementation | filtering-and-indexing | attribute | recursion | regular-expressions | invalid-list | working-with-file-paths | mapping-function | datetime.date,-datetime.time,-datetime.datetime | complex-number | syntax-error | floats | arithmetic-expression | overriding-methods | postfix | oops | threading | interpreter | sorting | loop | using-yield-in-functions | nested-loop | raise-statement | exception-handling | shallow-copy | staticmethod | regular-expression | recurssion | matplotlib | deep-copy | objects | type_conversion | sets | type-conversion | round | floating-point-precision | asyncio | assignment-operators | rollback | matrix | operand | random | arithmetic-operation | global | docstring | decorator | tuple-unpacking | syntaxerror | quantifiers-(*,-+,-?,-{}) | iterator | exponentiation | assignment-operator | math-copysign | data-structure | binary-operation | integer | round-function | loops | control-flow | bitwise-operator | with-statement | expand-tab | method-overloading | using-the-threading-module | logical-operators | while-loops | statement | sum-function | functions | complex | lambda-functions | arbitrary-arguments-(*args,-**kwargs) | literal-characters-and-special-characters | numpy | error | destructor | functional-programming | sys | mathematics | using-map()-for-transformations | conditional-statement | input | list,-set,-and-dictionary-comprehensions | assert | identity-operator | class-and-inheritance | using-lists-as-stacks | iterable | boolean | enumerate() | python-history | debugging | set | keyword | python | name-mangling | operator-overloading | immutable-data-type | lambda-function | conditional-statement | walking-through-directories-using-os.walk() | installation | using-else-and-finally | python-django | string-method | key-value-pairs | test-discovery | sorting-and-ranking | using-os-and-pathlib-modules | pickling--unpickling | binary | function | using-join()-and-is_alive()-methods | list-comprehension | oop | random-function | iterators | while-loop | mysql | global-keyword | virtual-environment | syntax | datatype | string-methods | creating-and-starting-threads | dictionary-methods | dictionaries | membership-operators-(in,-not-in) | booleans | multiple-except-blocks | sorted | zip | indexing | method | immutability | multiple-inheritance | built-in | for | memory-management | static-method | type-conversion-and-casting | multiple-inheritance | class-decorators | exception | tuple-methods | list-vs-tuple | decimal | regex | string-iteration | python-syntax-and-structure | string-formatting | min-function | math | boolean-and-non-boolean | feature | stack | asyncio-module | joining-and-merging-dataframes | object-attribute | precedence | python_version | list-mutation | async | bitwise-operator | python-module | typeerror | call | indexing:-loc-vs-iloc | collections | formal-and-actual-parameter | module | expression | syntax-error | global-variable | single-inheritance | virtual-environment | version-check | exception-handling | frozenset | version | pseudocode | thread-synchronization | string-concatenation | design-principle | gil | directory-operations | managing-directories-with-os-and-shutil | comparison | pep | append | python-repl | generators-in-python | dicts | datetime | dictionary | memory | software-design | print | data-structure | zfill-function | classes | file_handling | access-modifier | error-handling | conversion | condition | application | conditional-statements | pandas | zip-function | writing:-write(),-writelines() | return-statement | working-with-binary-files-(rb,-wb) | file | list-methods-and-slicing | opening-files-(open()) | sum() | string-manipulation | __future__ | logical-operation | integers | identity-operator | lambda | turtle | thread | command-line-parsing | parameter | namedtuple | constructor | yield | aggregating-data-with-functools.reduce() | map-function | advanced-file-operations | built-in-modules | list-indexing | reading-and-writing-large-files-efficiently | package-management | filter | magic-method | global-variable | difference-between-threads-and-processes | input-function | generator | mathematical-function | choice | basic | built-in-function | class | introduction-to-multiprocessing | slicing | list-join | while-and-for-loop | string-method | default-mutable-argument | data-structures-in-python | while-else-loop | loop-control | inheritance | center | list-operation | control-flow | list-comprehension | logical-operator | string-formatting | lists | boolean-masking | built-in-function | identifier | operations | using-assertions-(assertequal,-assertraises) | min-max-function | update | __all__-attribute | head-and-tail | strings | data-type | swapping | init | data_structure | overflow | scientific-notation | list | creating-custom-modules | namespace | match | inherit | __init_subclass__ | parsing-with-strptime | benefit | bitwise | join | class-and-instance-variable | heap-memory | unit-testing | input-function | working-with-temporary-files-using-tempfile | higher-order-function | indentation | raise | polymorphism | int | introduction-to-threads | pass | id-function | operator-and | operator-or | list-comprehensions | precedence-and-associativity | type-conversion | operators | error-handling | set-operation ...