What is Python Iteritems?
Iteritems in Python is a function that returns an iterator of the dictionary’s list. Iteritems are in the form of (keiy, value) tuple pairs. Python default dictionary iteration uses this method.
What’s a Dictionary in Python
Dictionaries in Python are unordered, changeable, and indexed—written with curly brackets having keys: value pair.
Example of dictionary in Python:
tdict = {
“brand” = “Honda”,
“model” = “Pleasure”,
“year”= “2006”
}
Explanation
Here brand, model, and year are the tdict dictionary’s keys. And Honda, Pleasure, and 2006 are their respective values.
Loops and iteritems() can be used to create a dictionary in Python.
dict.items() Vs. dict.iteritems() in Python
Both the function does almost the same thing, i.e., dictionary iteration, with a very slight difference between them –
dict.items() – This function returns a copy of the dictionary’s list. It is present in the Python 3 version and exists in the Python 2 versions.
dict.iteritems() – This function returns an iterator of the dictionary’s list. It is a python 2 version feature and got omitted in the Python 3 versions.
Note: Python’s future library ensures compatibility with Python 2.6/2.7 and 3.x versions. Python’s future module has much stuff already done in an optimized way.
Python 2 code to demonstrate dict.iteritems():
dict ={
"Name": "Riya",
"City": "New York",
"Country": "USA"
}
for i in dict.iteritems():
# prints the items
print(i)
Output:
('Name', 'Riya')
('City', 'New York')
('Country', 'USA')
Python 3 code to demonstrate dict.items():
dict ={
"Name": "Riya",
"City": "New York",
"Country": "USA"
}
print("d.items() = ")
for i in dict.items():
# saves as a copy
print(dict.items())
Output:
dict_items([(‘Name’, ‘Riya’), (‘City’, ‘New York’), (‘Country’, ‘USA’)])
Explanation:
The above two python codes demonstrate the use of dict.iteritems() and dict.tems() in Python 2 and Python 3. dict.items() works in python 2 but never generates the list entirely. As a result, no one uses it. However, using dict.iteritems() does not create any result and raises an error.
Is Itertools Infinite in Python?
Itertools used for iterations present in the python 3 library are infinite iterators like count(), cycle(), repaeat(). Iterators terminating on shortest input sequence like accumulate(), chain(), compress(), dropwhile(), filterfalse(),islice(), strmap(),etc each having very unique distinct results. Combinaton iterators presenting the iterator module of python are product(), permutations(), combinations() and combination_with_replacement().
Errors while importing itertools in Python
While importing itertools into a python program, numerous errors crop up, the most common one being attribute error. Wrong module name or importing the faulty module generates attribute errors. As a result, you have to use the exception handling technique and iteritems while iteration of long lists in dictionaries to avoid AttributeError.
- in Python 3
In Python, items() is time-consuming and memory exhausting. The items() function returns a copy, whereas iteritems() is less time consuming and less memory exhausting. However, since items() performed almost the same task as iteritems(). The latter has been removed from Python 3. Now, items() return iterators and never builds a list entirely in Python 3.
dict.iteritems() to dict .items() in Python 3
If one uses Python 3, It’s common to incur an attribute error reading ‘dict’ has no attributes’ iteritems.’ This error is so because in python 3 the functionality of dict.iteritems() has been transferred to dict.items(). Programmers need to use dict.items() for iteration of the dictionary while working in python 3. Python 3 no longer have dict.iteritems(). Thus can no longer be used. dict.iterkeys() and dict.itervalues() have also been removed from Python 3. Instead one needs to use dict.keys() and dict.values() for error-free execution of the program.
Both .items() and .iteritems() in Python 2
In python 2, both .items() and .iteritems() functions are available. dict.items() copied all tuples to create the new list, which had a huge memory impact. The later versions of python 2 created dict.iteritems(), which returned just the iterator objects. Thus consuming less memory and making the programs more efficient.
DataFrame in Python
DataFrame is a two-dimensional data structure with rows and columns of potentially different types. It is the most commonly used Pandas object or by importing values from an excel file. The first line of creation of DataFrame in both methods requires import pandas in the program. For example – import pandas as PD as the first line and DataFrame creation as df = PD.DataFrame().
DataFrame.iteritems()
DataFrame.iteritems() or DataFrame.items() iterates over data frame columns, i.e. (column name, series) pairs are returning a tuple with the column name and the content as a series. Dataframes preserves the data type of elements along its column. DataFrame.iterrows iterates over(index, series) pairs yielding an index of the row and the row’s data as a series. Since iterrows returns a series for each row, it does not preserve data types across the rows.
intertupes() are better used to preserve data while iterating over rows. Intertupes() iterates over rows as named tuples, with the first field being index. And the following fields being column values and is generally faster than iterrows. Since we can iterate over DataFrames like dictionary using the above functions. DataFrames uses key-value pairs to compare them.
Dictionary sorting using python iteritems()
Dictionaries in Python are unsorted and iteritems() function can help to do it.
• Sorting by key – Method iteritems() returns an iterator of the key-value tuples. Applying the sorted() function to the return value returns a list of tuples sorted by key.
• Sorting by value – Specifying a comparison function to the sorted(). The function that receives two tuples to compare uses cmp() to compare each second element. Thus, sorting by value.
Note:
Python iteritems is a (Python v2. x) version and got omitted in (Python v3. x) version.
Must Read
- Introduction to Python Super With Examples
- Python Help Function
- Why is Python sys.exit better than other exit functions?
- Python Bitstring: Classes and Other Examples | Module
Conclusion
In this article, we learned what python iteritems is. We also learned the difference between dict.items() and dict.iteritems(). In conclusion, we can say Dict.items() yields a list of tuples. It’s time-consuming and memory exhausting, whereas dict.iteritems() is an iter-generator method that yields tuples also. It’s time-consuming and less memory exhausting.
Still have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.
Happy Python!