Http://btmiller.com/2015/04/13/get-list-of-keys-from-dictionary-in-python-2-and-3.html
Get a List of Keys from a Dictionary in Both Python 2 and Python 3
It was mentioned in an earlier post this there is a difference on how the keys()
operation behaves between Python 2 and Pyt Hon 3. If you ' re adapting your Python 2 code to Python 3 (which you should), it'll throw a When you TypeError
try to operate on like a List. so, If you depend on getting a list returned from, Here's How to make it work for keys()
both Python 2 and Python 3.
In Python 2, simply calling on keys()
a Dictionary object would return what do you expect:
$ python>>> foo = { ‘bar‘: "hello", ‘baz‘: "world" }>>> type(foo.keys())<type ‘list‘>>>> foo.keys()[‘baz‘, ‘bar‘]>>> foo.keys()[0]‘baz‘
That's great, however, in Python 3, keys()
no longer returns a list, but a view object:
The objects returned dict.keys()
by, and is dict.values()
dict.items()
view Objects. They provide a dynamic view on the Dictionary's entries, which means that's when the dictionary changes, the view reflects T Hese changes.
The object is an iterator and looks a lot more like dict_keys
a set
than a list
. So using the same call in Python 3 would produce this result:
$ python3>>> foo = { Bar ': "hello", ' baz ': "world" >>> type (foo.keys ()) <class ' Dict_keys ' >>>> foo.keys () dict_keys ([ Span class= "s1" > ' baz ', ' bar ' ]) >>> Foo.keys () [0]traceback (most recent call Lastin <module>typeerror: ' Dict_keys ' object does not support Indexing
The typeerror
can be avoided and compatibility can be maintained By simply converting The dict_keys
object to a list which can then be Indexed as normal in both Python 2 and Python 3:
$ python3>>> foo = { ‘bar‘: "hello", ‘baz‘: "world" }>>> type(list(foo.keys()))<class ‘list‘>>>> list(foo.keys())[‘baz‘, ‘bar‘]>>> list(foo.keys())[0]‘baz‘
And just for good measure, here it's in Python 2:
$ python>>> foo = { ‘bar‘: "hello", ‘baz‘: "world" }>>> type(list(foo.keys()))<class ‘list‘>>>> list(foo.keys())[‘baz‘, ‘bar‘]>>> list(foo.keys())[0]‘baz‘
Http://stackoverflow.com/questions/16819222/how-to-return-dictionary-keys-as-a-list-in-python-3-3
65down Votefavorite6 |
I noticed something very weird-or let's say, something that's very different from Python 2.7 and older versions of Pyth On 3 I Believe. previously, I could get dictionary keys, values, or items of a dictionary very easily as List: Python2.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 PYTHON 3.3.0>>> newdict.keys()dict_keys([1, 2, 3])
I am wondering if there is a by-return a list as I showed it in the Python 2.7 example. Because now, I had to does something like newlist = list()for i in newdict.keys(): newlist.append(i)
EDIT: Thanks, list(newdict.keys()) works as I wanted! But there was another thing that bugs me now:i want to create a list of reversed dictionary keys and values to sort them b Y Values. Like so (okay, this was a bad example, because the values were all 0 here) >>> Zip (newdict. Values (), Newdict. () [(0 1 ( 0, 2 (0, 3 /span>
however, in Python3 I get something like >>> zip(list(newdict.keys()), list(newdict.values()))<zip object at 0x7f367c7df488>
Okay, sorry, I just figured out, which you had to use a list() function around zip() too. list ( Zip (newdict. Values (), Newdict. ()) [(0 1 ( 0, 2 (0, 3 /span>
This is really something one have to get used to List Dictionary python-3.x python-2.x
ShareImprove this question |
Edited ' at 16:38 |
Asked ' at 16:24 user2015601 |
|
|
if you ' re trying to sort A dictionary by values, try this oneliner: 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 a key parameter which Should be a function this transforms each list element into the value which should is used to sort. – chris ; may "at 17:33 |
|
|
Looks very handy, thanks! – user2015601 ' at 18:54 |
|
Interesting thread safety issue regarding this topic was here:blog.labix.org/2008/06/27/...–paul may at 18:00 |
Add a Comment |
3 answersactiveoldestvotes
Up vote78down voteaccepted |
Try list(newdict.keys()) . This wil convert the Dict_keys object to a List. On the other hand, you should ask yourself whether or not it matters. The Pythonic-assume duck typing (if it looks like a duck and it quacks like a duck, it s a duck ). The Dict_keys object would act like a list for most purposes. For instance: for key in newdict.keys(): print(key)
Obviously insertion operators may not be work, but the doesn ' t make much sense for a list of dictionary keys Anyway.
ShareImprove this answer |
answered ' at 16:25Chris1,787 7 |
|
|
|
thank you for the quick response, it works! Regarding the second part of your answer:i think it matters for what I want to does with the list (s), I updated my question Under the EDIT Section. Thanks! – user2015601 May 29 ' 13 At 16:31 |
newdict.keys () does not s Upport indexing – miguel de val-borro Sep "at 17:54 " /span> |
|
|
list(newdict) Also works (at least in Python 3.4). Is there any reason to use the .keys() method?–naught101 Mar ' at 11:58 |
|
How to return dictionary keys as a list in Python 3.3