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()
anddict.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:
Now, I get something like this in
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
EDIT: Thanks, 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)
However, in Python3 I get something like
Okay, sorry, I just figured out that you have to use a
This is really something one has to get used to
|
|||||||||||||
|
Try 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:
Obviously insertion operators may not work, but that doesn't make much sense for a list of dictionary keys anyway. |
|||||||||||||
|
How to return dictionary keys as a list in Python 3.3的更多相关文章
- Python 字典(Dictionary) keys()方法
Python 字典(Dictionary) keys() 函数以列表返回一个字典所有的键. 语法 keys()方法语法: dict.keys() 参数 NA. 返回值 返回一个字典所有的键. 实例 以 ...
- 【RF库Collections测试】Get Dictionary Keys
Name:Get Dictionary KeysSource:Collections <test library>Arguments:[ dictionary ]Returns `keys ...
- c# LRU实现的缓存类
在网上找到网友中的方法,将其修改整理后,实现了缓存量控制以及时间控制,如果开启缓存时间控制,会降低效率. 定义枚举,移除时使用 public enum RemoveType { [ ...
- Java自定义一个字典类(Dictionary)
标准Java库只包含Dictionary的一个变种,名为:Hashtable.(散列表) Java的散列表具有与AssocArray相同的接口(因为两者都是从Dictionary继承来的).但有一个方 ...
- 字典集合Dictionary<K,V>和构造的应用==>>体检套餐项目
效果 首先,我们先来准备我们需要的类 1.检查项目类 using System; using System.Collections.Generic; using System.Linq; using ...
- Python dictionary implementation
Python dictionary implementation http://www.laurentluce.com/posts/python-dictionary-implementation/ ...
- 自定义Dictionary支持线程安全
本文转载:http://www.cnblogs.com/kiddo/archive/2008/09/25/1299089.html 我们说一个数据结构是线程安全指的是同一时间只有一个线程可以改写它.这 ...
- javascript字典数据结构Dictionary实现
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat=&qu ...
- JavaScript 字典(Dictionary)
TypeScript方式实现源码 // set(key,value):向字典中添加新元素. // remove(key):通过使用键值来从字典中移除键值对应的数据值. // has(key ...
随机推荐
- JS数组的concat、push等方法,操作的是地址指针,而非内存操作
var a = [{x:1}, {y:1}, {z:3}]; var b = a.concat(['gg', 'ff']); var c = []; c.push(a[1]); console.log ...
- Linux 容器技术史话:从 chroot 到未来
Linux 容器是一个在单一 Linux 主机上提供多个隔离的 Linux 环境的操作系统级虚拟技术.不像虚拟机(VM),容器并不需要运行专用的访客(guest)操作系统.容器们共享宿主机的(host ...
- Redis的介绍及使用实例.
本文就来讲一下Redis安装的方法和Redis生成主键的优点以及和其他几种方式生成主键的对比. 1,Redis安装首先将Redis的tar包拷贝到Linux下的根目录 然后解压到redis文件夹下:( ...
- Atiti attilax主要成果与解决方案与案例rsm版 v2
Atiti attilax主要成果与解决方案与案例rsm版 v2 1. ##----------主要成果与解决方案与 参与项目1 ###开发流程与培训系列1 #-----组织运营与文化建设系列1 # ...
- iOS开发——高级技术精选OC篇&Runtime之字典转模型实战
Runtime之字典转模型实战 如果您还不知道什么是runtime,那么请先看看这几篇文章: http://www.cnblogs.com/iCocos/p/4734687.html http://w ...
- js 判断字符串是否包含另外一个字符串
示例代码: <script type="text/javascript"> var str = "测试一个字符串(ehtrzes)是否包含另外一个字符串&qu ...
- 执行SSIS Package的三种方式
1,使用SQL Server job 创建一个job用于执行package,可以制定一个schedule来定时执行job,也可以使用TSql 代码来执行job EXEC msdb.dbo.sp_sta ...
- ProgressBar 源码
/** * @FileName CircleProgressBar.java * @Package com.read.view * @Description TODO * @Author Alpha ...
- javascript类型系统——undefined和null
× 目录 [1]原因 [2]undefined [3]null 前面的话 一般的程序语言,表示空的只有null,但javascript的设计者Brendan Eich却设计了一个undefined,这 ...
- Kruskal算法(三)之 Java详解
前面分别通过C和C++实现了克鲁斯卡尔,本文介绍克鲁斯卡尔的Java实现. 目录 1. 最小生成树 2. 克鲁斯卡尔算法介绍 3. 克鲁斯卡尔算法图解 4. 克鲁斯卡尔算法分析 5. 克鲁斯卡尔算法的 ...