I was practising with enumerate()
and dictionaries in python. When I do not print out the enumerated data I am able to create a dictionary from the enumerated data. But when I do print out the enumerated data, I am no longer able to create a dictionary. Why would that be?
For when I do not print out my enumerated data:
data = ['a','b','c','d']
enum_data = enumerate(data, 1)
data_dict = dict(enum_data)
print("Data Dict: ", data_dict)
print("Should be 'a': ", data_dict.get(1))
My output is
Data Dict: {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
Should be 'a': a
But when I do not:
data = ['a','b','c','d']
enum_data = enumerate(data, 1)
for enum, point in enum_data:
print("Count: ", enum, " ", "Element: ", point)
data_dict = dict(enum_data)
print("Data Dict: ", data_dict)
print("Should be 'a': ", data_dict.get(1))
I get:
Count: 1 Element: a
Count: 2 Element: b
Count: 3 Element: c
Count: 4 Element: d
Data Dict: {}
Should be 'a': None
enumerate
returns an iterator. An iterator may only be iterated over once.
A common solution is to use itertools.tee
to return an arbitrary number of independent iterators:
from itertools import tee
data = ['a','b','c','d']
enum_data1, enum_data2 = tee(enumerate(data, 1), 2)
for enum, point in enum_data1:
print("Count: ", enum, " ", "Element: ", point)
data_dict = dict(enum_data2)
print("Data Dict: ", data_dict) # {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
print("Should be 'a': ", data_dict.get(1)) # a