user17500663
user17500663

Reputation:

Iterate dict in python using next()

Is it possible to iterate dictionary in python using next(). (I need to access keys and values). Also would it work for extendable dictionaries with non-fixed length?

Upvotes: 4

Views: 6597

Answers (2)

azro
azro

Reputation: 54148

Use items to get the pairs key/value and iter() to be able to call next

content = dict(zip(range(10), range(10, 20)))
print(content)  # {0: 10, 1: 11, 2: 12, 3: 13, 4: 14, 5: 15, 6: 16, 7: 17, 8: 18, 9: 19}

iterable = iter(content.items())
print(next(iterable))  # (0, 10)
print(next(iterable))  # (1, 11)
print(next(iterable))  # (2, 12)
print(next(iterable))  # (3, 13)

Upvotes: 8

ForceBru
ForceBru

Reputation: 44838

  1. Yes, it is possible to iterate over a dictionary using next (and iter). In fact, this is how iteration works:

    1. Obtain an iterator: __it = iter(your_dict)
    2. Call next(__it) to retrieve the next key
  2. Iterating over a dictionary iterates over its keys: list({1: 'hello', 2: 'world'}) == [1, 2]. You should iterate over your_dict.items() to get pairs of keys and values

Upvotes: 0

Related Questions