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