3

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.

Community
  • 1
  • 1
Tommy
  • 12,588
  • 14
  • 59
  • 110
  • just use `result = list(zip(*iterable_of_pairs))` or even shorter `result_a, result_b = zip(*iterable_of_pairs)` – Semnodime Feb 02 '23 at 09:51
  • apparently having the `[…]` around the generator expression is what provides you inconvenience, simply remove it. – Semnodime Feb 02 '23 at 09:52
  • Note: `[stuff]` won't transform the iterable `stuff` into a `list`, it only *creates* a list, with `stuff` as its first element. use `list(stuff)` instead. – Semnodime Feb 02 '23 at 09:54

1 Answers1

9

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]
Semnodime
  • 1,872
  • 1
  • 15
  • 24
dawg
  • 98,345
  • 23
  • 131
  • 206
  • 2
    You need `from operator import itemgetter` to use [itemgetter](https://docs.python.org/2/library/operator.html#operator.itemgetter) – dawg Jan 04 '16 at 02:00