Python Iteritems And dict.items() Vs. dict.iteritems()

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 (key, value) tuple pairs. This function is used in python for dictionary iteration.

What’s a Dictionary in Python

Dictionaries in python are collections that are unordered, changeable, and indexed. They are 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 keys of the tdict dictionary. And Honda, Pleasure, and 2006 are their respective values.

Now, dictionary iteration can be done in two ways: using for loops and using iteritems().

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 is used nowadays to ensure 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": "Mumbai", 
"Country": "India"
} 
  
for i in dict.iteritems(): 
      
    # prints the items 
    print(i) 

Output:

('Name', 'Riya')
('City', 'Mumbai')
('Country', 'India')

Python 3 code to demonstrate dict.items():

dict ={ 
"Name": "Riya", 
"City": "Mumbai", 
"Country": "India"
  } 

print("d.items() = ") 
for i in dict.items(): 

# saves as a copy 
print(dict.items()) 

Output:

dict_items([(‘Name’, ‘Riya’), (‘City’, ‘Mumbai’), (‘Country’, ‘India’)])

Explanation:

Above two python codes demonstrates the use of dict.iteritems() and dict.tems() in Python 2 and Python 3 respectively. dict.items() works in python 2 but never generates the list fully so is not used usually. However using dict.iteritems() does not generate any result and raises an error.

Are 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. Attribute errors usually occur if the wrong module name has been used or due to importing the wrong module. Attribute error is also used as an exception handling technique along with iteritems while iteration of long lists in dictionaries.

items() 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 that of iteritems(). The latter has been removed from Python 3. Now, items() return iterators and never builds a list fully in Python 3.

dict.iteritems() to dict .items() in Python 3

If one is using Python 3, It’s common to incur an attribute error reading ‘dict’ has no attributes ‘iteritems’. This 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. The dict.iteritems() has been removed from python 3. 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. Pandas DataFrame is created in python either by typing the values in python itself. Or by importing values from an excel file. The first line of creation of DataFrame in both the method 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 returning a tuple with the column name and the content as a series. Datatypes are preserved across columns for dataframes. 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.

To preserve datatypes while iterating over rows, intertupes() are better to be used. 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 can also be compared by calling key-value pairs.

Dictionary sorting using python iteritems()

Dictionaries in python are unsorted and can be sorted by various methods using the iteritems() function.
Sorting by key – Method iteritems() returns an iterator of the key-value tuples. So 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 which receives two tuples to compare uses cmp() to compare the second element of each. Thus, sorting by value.

Note:

Python iteritems is a (Python v2. x) version and got omitted in (Python v3. x) version.

Must Read

Conclusion

In this article, we learned what python iteritems is. We also learned the difference between dict.items() and dict.iteritems(). So, in conclusion, we can say Dict.items() yields a list of tuples and it’s time-consuming and memory exhausting whereas, dict.iteritems() is an iter-generator method that yield 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 Pythoning!


0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
x