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