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