Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python3 unzipping a list of tuples

Tags:

python-3.x

In python2.7, the following code takes the dictionary fd (in this example representing a frequency distribution of words and their counts), and separates it into a list of two lists: [[the keys],[values]]:

sortedDKandVs = [zip(*sorted(fd.items(), key=itemgetter(1), reverse=True))] #[word,word,...],[count,count]

I can then do, for example:

keys = sortedDKandVs[0]
values = sortedDKandVs[1]

This no longer works in Python3 and I want to know how to transform the code.

None of the answers here How to unzip a list of tuples into individual lists? work anymore because in Python3 zip objects return iterators instead of lists, but I am not sure how to transform the answers.

like image 933
Tommy Avatar asked Oct 22 '25 04:10

Tommy


1 Answers

Python 2:

Python 2.7.6 (default, Apr  9 2014, 11:48:52) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from operator import itemgetter
>>> di={'word1':22, 'word2':45, 'word3':66}
>>> zip(*sorted(di.items(), key=itemgetter(1), reverse=True))
[('word3', 'word2', 'word1'), (66, 45, 22)]
>>> k,v=zip(*sorted(di.items(), key=itemgetter(1), reverse=True))
>>> k
('word3', 'word2', 'word1')
>>> v
(66, 45, 22)

Python 3:

Python 3.4.1 (default, May 19 2014, 13:10:29) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from operator import itemgetter
>>> di={'word1':22, 'word2':45, 'word3':66}
>>> k,v=zip(*sorted(di.items(), key=itemgetter(1), reverse=True))
>>> k
('word3', 'word2', 'word1')
>>> v
(66, 45, 22)

It is exactly the same for both Python 2 and Python 3

If you want lists vs tuples (both Python 3 and Python 2):

>>> k,v=map(list, zip(*sorted(di.items(), key=itemgetter(1), reverse=True)))
>>> k
['word3', 'word2', 'word1']
>>> v
[66, 45, 22]
like image 170
dawg Avatar answered Oct 26 '25 15:10

dawg