How to return dictionary keys as a list in Python 3.3

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 that there is a difference in how the keys() operation behaves between Python 2 and Python 3. If you’re adapting your Python 2 code to Python 3 (which you should), it will throw a TypeError when you try to operate on keys() like a list. So, if you depend on getting a list returned from keys(), here’s how to make it work for both Python 2 and Python 3.

In Python 2, simply calling keys() on a dictionary object will return what 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 by dict.keys()dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

The dict_keys object is an iterator and looks a lot more like 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([‘baz‘, ‘bar‘])
>>> foo.keys()[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <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 into 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 is 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 votefavorite

6

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

list dictionary python-3.x python-2.x


shareimprove this question

edited May 29 ‘13 at 16:38

asked May 29 ‘13 at 16:24

user2015601

 

1  

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 that transforms each list element into the value which should be used to sort. – ChrisMay 29 ‘13 at 17:33 
    

Looks very handy, thanks! – user2015601 May 29 ‘13 at 18:54
    

Interesting thread safety issue regarding this topic is here: blog.labix.org/2008/06/27/… – Paul May 10 at 18:00

add a comment

3 Answers

activeoldestvotes


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 way to code is to assume duck typing (if it looks like a duck and it quacks like a duck, it‘s a duck). the dict_keys object will act like a list for most purposes. For instance:

for key in newdict.keys():
  print(key)

Obviously insertion operators may not work, but that doesn‘t make much sense for a list of dictionary keys anyway.


shareimprove this answer

answered May 29 ‘13 at 16:25

Chris

1,787714

 

    

Thank you for the quick response, it works! Regarding the second part of your answer: I think it matters for what I want to do with the list(s), I updated my question under the EDIT section. Thanks! – user2015601 May 29 ‘13 at 16:31 
1  

newdict.keys() does not support indexing – Miguel de Val-Borro Sep 10 ‘14 at 17:54
5  

list(newdict) also works (at least in python 3.4). Is there any reason to use the .keys() method? – naught101 Mar 31 ‘15 at 11:58 

时间: 2024-10-17 09:19:57

How to return dictionary keys as a list in Python 3.3的相关文章

Python dictionary implementation

Python dictionary implementation http://www.laurentluce.com/posts/python-dictionary-implementation/ August 29, 2011 This post describes how dictionaries are implemented in the Python language. Dictionaries are indexed by keys and they can be seen as

JavaScript Dictionary

function Dictionary() { var items = {}; this.has = function(key) { return key in items } this.set = function(key, value) { items[key] = value } this.remove = function(key) { if (this.has(key)) { delete items[key]; return true } return false } this.ge

字典集合Dictionary&lt;K,V&gt;和构造的应用==&gt;&gt;体检套餐项目

效果 首先,我们先来准备我们需要的类 1.检查项目类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 第五章_体检套餐管理系统_ { //项目类 public class HealthCheckItem { //项目描述 public string Description { get; set;

JS字典 Dictionary类

字典 Dictionary类 /*字典 Dictionary类*/ function Dictionary() { this.add = add; this.datastore = new Array(); this.find = find; this.remove = remove; this.showAll = showAll; this.count = count; this.clear = clear; } function add(key, value) { this.datastor

将Object转换成Dictionary方法

如果Object是Dictionary类型,直接返回 如果Object是NameValueCollection类型,则添加到Dictionary里 如果Object是Hashtable类型,添加到Dictionary里 ...其他键值类型请自己完善 如果Object非上述类型,则用IL语言将其转换成Dictionary类型, 具体代码如下: public static Dictionary<string, object> ConvertFromObject(object obj) { if (

Dictionary(字典)

Dictionary(字典) 字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据.python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的.可哈希表示key必须是不可变类型,如:数字.字符串.元组. 字典(dictionary)是除列表意外python之中最灵活的内置数据结构类型.列表是有序的对象结合,字典是无序的对象集合.两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取. 创

Json字符串转Dictionary

/// <summary> /// json字符串转Dictionary /// </summary> /// <param name="json"></param> /// <returns></returns> public static Dictionary<string, object> getValue(string json) { //解析json对象 JavaScriptSerialize

03集合:List&lt;T&gt;,Dictionary&lt;K,V&gt;

List<T>泛型集合 List<T>是C#中一种快捷.易于使用的泛型集合类型,使用泛型编程为编写面向对象程序增加了极大的效率和灵活性. 1.List<T>用法 (1)创建一个List<T>泛型集合对象实例 List<T> list = new List<T>();// T 为列表中元素的类型 List<string> mlist = new List<string>();//创建了一个 string 类型的集

Silverlight系列--动态生成DataGrid列 根据动态列绑定Dictionary数据

1.获取表头数据源动态生成DataGrid表头 DataGridTextColumn d = new DataGridTextColumn(); d.Header = itemPriceClass.PriceKindCode + itemPriceClass.PriceKindName; Binding bin = new Binding(); bin.Converter = new RowIndexConverter(); bin.ConverterParameter = itemPriceC