I noticed something very weird - or let's say, something that is very different from Python 2.7 and older versions of Python 3 I believe.
Previously, I could get dictionary keys, values, or items of a dictionary very easily as list:
PYTHON 2.7
>>> newdict = {1:0, 2:0, 3:0}
>>> newdict
{1: 0, 2: 0, 3: 0}
>>> newdict.keys()
[1, 2, 3]
Now, I get something like this in
PYTHON 3.3.0
>>> newdict.keys()
dict_keys([1, 2, 3])
I am wondering if there is a way to return a list as I showed it in the Python 2.7 example. Because now, I have to do something like
newlist = list()
for i in newdict.keys():
newlist.append(i)
EDIT:
Thanks, list(newdict.keys())
works as I wanted!
But there is another thing that bugs me now: I want to create a list of reversed dictionary keys and values to sort them by values. Like so (okay, this is a bad example, because the values are all 0 here)
>>> zip(newdict.values(), newdict.keys())
[(0, 1), (0, 2), (0, 3)]
However, in Python3 I get something like
>>> zip(list(newdict.keys()), list(newdict.values()))
<zip object at 0x7f367c7df488>
Okay, sorry, I just figured out that you have to use a list()
function around zip()
too.
list(zip(newdict.values(), newdict.keys()))
[(0, 1), (0, 2), (0, 3)]
This is really something one has to get used to
sorted(newdict.item?s(),key=lambda x: x[1])
.newdict.items()
returns the key-value pairs as tuples (just like you're doing with the zip above).sorted
is the built-in sort function and it permits akey
parameter which should be a function that transforms each list element into the value which should be used to sort. – Chris May 29 '13 at 17:33