Skip to content Skip to sidebar Skip to footer

Python3 Unzipping A List Of Tuples

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 list

Solution 1:

Python 2:

Python 2.7.6 (default, Apr  92014, 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.
>>> 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 192014, 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.
>>> 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]

Post a Comment for "Python3 Unzipping A List Of Tuples"