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

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

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

3 Answers

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.

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 

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

  1. Python 字典(Dictionary) keys()方法

    Python 字典(Dictionary) keys() 函数以列表返回一个字典所有的键. 语法 keys()方法语法: dict.keys() 参数 NA. 返回值 返回一个字典所有的键. 实例 以 ...

  2. 【RF库Collections测试】Get Dictionary Keys

    Name:Get Dictionary KeysSource:Collections <test library>Arguments:[ dictionary ]Returns `keys ...

  3. c# LRU实现的缓存类

    在网上找到网友中的方法,将其修改整理后,实现了缓存量控制以及时间控制,如果开启缓存时间控制,会降低效率. 定义枚举,移除时使用 public enum RemoveType    {        [ ...

  4. Java自定义一个字典类(Dictionary)

    标准Java库只包含Dictionary的一个变种,名为:Hashtable.(散列表) Java的散列表具有与AssocArray相同的接口(因为两者都是从Dictionary继承来的).但有一个方 ...

  5. 字典集合Dictionary<K,V>和构造的应用==>>体检套餐项目

    效果 首先,我们先来准备我们需要的类 1.检查项目类 using System; using System.Collections.Generic; using System.Linq; using ...

  6. Python dictionary implementation

    Python dictionary implementation http://www.laurentluce.com/posts/python-dictionary-implementation/ ...

  7. 自定义Dictionary支持线程安全

    本文转载:http://www.cnblogs.com/kiddo/archive/2008/09/25/1299089.html 我们说一个数据结构是线程安全指的是同一时间只有一个线程可以改写它.这 ...

  8. javascript字典数据结构Dictionary实现

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat=&qu ...

  9. JavaScript 字典(Dictionary)

    TypeScript方式实现源码 //  set(key,value):向字典中添加新元素. //  remove(key):通过使用键值来从字典中移除键值对应的数据值. //  has(key ...

随机推荐

  1. Java Socket Server的演进 (一)

    最近在看一些网络服务器的设计, 本文就从起源的角度介绍一下现代网络服务器处理并发连接的思路, 例子就用java提供的API. 1.单线程同步阻塞式服务器及操作系统API 此种是最简单的socket服务 ...

  2. IOS Animation-贝塞尔曲线与Layer简单篇(一)

    IOS Animation-贝塞尔曲线与Layer简单篇 swift篇 1.介绍 贝塞尔曲线: 贝塞尔曲线是计算机图形图像造型的基本工具,是图形造型运用得最多的基本线条之一.它通过控制曲线上的四个点( ...

  3. jQuery的extend方法的深层拷贝

    一些东西长时间不用就忘了,比如这个jQuery的extend方法的深层拷贝,今天看单页应用的书的时候,看到entend第一个参数是true,都蒙了.也是,自己的大部分对jQuery的学习知识来自锋利的 ...

  4. Lua字符串库(整理)

    Lua字符串库小集 1. 基础字符串函数:    字符串库中有一些函数非常简单,如:    1). string.len(s) 返回字符串s的长度:    2). string.rep(s,n) 返回 ...

  5. C++中如何定义类和对象?

    在C++语言中,对象的类型被称为类,类代表了某一批对象的共性和特征. 类是对象的抽象,而对象是类的具体实例.如同C中的结构体一样,我们要先定义一个结构体,再使用结构体去定义一个变量.同一个结构体可以定 ...

  6. 解析大型.NET ERP系统 窗体、查询、报表二次开发

    详细介绍Enterprise Solution 二次开发的流程步骤,主要包括数据输入窗体(Entry Form),查询(Query/Enquiry),报表(Report)三个重要的二次开发项目. 数据 ...

  7. maven项目部署打包

    方法一.把maven依赖的jar包一起打包 http://maven.apache.org/plugins/maven-assembly-plugin/usage.html pom/build中加入以 ...

  8. Android Service小记

    Service 是Android 的一种组件,跟线程无关. Service 分两种启动方式 startService()和bindService() 两种都需要在Androidmanifest.xml ...

  9. Cocos2d-x 3.2 学习笔记(一)环境搭建

    目前项目无事,时间比较充裕,因此来学习下cocos2dx,当然本人也是新手一个, 写此笔记做备忘和脚步. 最近3.2版本更新出來了!官方说这是自2.x分支以来修复了超过450个bug,3.2版本是目前 ...

  10. NSIS使用教程(安装包制作安装文件教程,如何封装打包文件) 中文版

    nsis中文版(Nullsoft Scriptable Install System)是一个专业的开源的可以用来封闭Windows程序的实用工具,是一个开源的 Windows 系统下安装程序制作程序. ...