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