How to return dictionary keys as a list in Python 3.3

来源:http://www.cnblogs.com/kungfupanda/archive/2016/08/17/5779966.html
-Advertisement-
Play Games

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 Pytho ...


 

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

   
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. – Chris May 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 

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 最近簡單的對oracle,mysql,sqlserver2005的數據分頁查詢作了研究,把各自的查詢的語句貼出來供大家學習..... (一)、 mysql的分頁查詢 mysql的分頁查詢是最簡單的,藉助關鍵字limit即可實現查詢,查詢語句通式: 如下麵的截圖,每頁顯示的記錄數為20: 查詢(1-2 ...
  • MySQL外鍵使用及說明 一、外鍵約束 MySQL通過外鍵約束來保證表與表之間的數據的完整性和準確性。 外鍵的使用條件: 1.兩個表必須是InnoDB表,MyISAM表暫時不支持外鍵(據說以後的版本有可能支持,但至少目前不支持); 2.外鍵列必須建立了索引,MySQL 4.1.2以後的版本在建立外鍵 ...
  • MongoDB只提供了64位LTS(長期支持)Ubuntu發行版的packages。例如,12.04 LTS,14.04 LTS,16.04 LTS等等。 1.導入被包管理系統使用的公鑰 Ubuntu軟體包管理工具(例如:dpkg和apt)通過要求經銷商使用GPG密鑰簽署包以確保方案的一致性和真實性 ...
  • 1.建立Java工程 使用idea,添加lib庫,拷貝storm中lib到工程中 2.拷貝wordcount代碼 下載src包,解壓找到 apache-storm-0.9.4-src\apache-storm-0.9.4\examples\storm-starter\src\jvm\storm\st ...
  • 有兩張表A和B,要求往A裡面插入一條記錄的同時要向B裡面也插入一條記錄,向B裡面插入一條記錄的同時也向A插入一條記錄。兩張表的結構不同,需要將其中幾個欄位對應起來。可以用下麵的觸發器實現。 表A的觸發器: 表B的觸發器: ...
  • 查看MySQL二進位文件中的內容有兩種方式 1. mysqlbinlog 2. SHOW BINLOG EVENTS [IN 'log_name'] [FROM pos] [LIMIT [offset,] row_count] 下麵來測試一下,在mysql中執行如下操作 對應二進位日誌中的內容如下 ...
  • 從MySQL 5.5遷移到Mariadb 10.1.14 遷移計劃如下: 1.備份MySQL 5.5的資料庫,對指定庫進行備份。 2.還原到Mariadb,然後建立複製。 3.然後就可以願意啥時候切換就啥時候切換。 遇到的問題: 因為一般都是innodb,所以我想用xtrabackup工具備份。備份 ...
  • 1.NoSql簡介 NoSql(Not Only Sql)指的是非關係型的資料庫。下一代資料庫主要解決幾個要點:非關係型的、分散式的、開源的、水平可擴展的。原始的目的是為了大規模web應用,這場 運動開始於2009年初,通常特性應用如:模式自由、支持簡易複製、簡單的API、最終的一致性(非ACID) ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...