Skip to content
Fix Code Error

How to return dictionary keys as a list in Python?

March 13, 2021 by Code Error
Posted By: user2015601

In Python 2.7, I could get dictionary keys, values, or items as a list:

>>> newdict = {1:0, 2:0, 3:0}
>>> newdict.keys()
[1, 2, 3]

Now, in Python >= 3.3, I get something like this:

>>> newdict.keys()
dict_keys([1, 2, 3])

So, I have to do this to get a list:

newlist = list()
for i in newdict.keys():
    newlist.append(i)

I’m wondering, is there a better way to return a list in Python 3?

Solution

Try list(newdict.keys()).

This will 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 By: Anonymous

Related Articles

  • Polymer- App Route with Sub Paging
  • How do I include certain conditions in SQL Count
  • How to append multiple items in one line in Python
  • How do I merge two dictionaries in a single…
  • How to create a property for a List
  • In CSS Flexbox, why are there no "justify-items" and…
  • How to convert number to words in java
  • Why does C++ code for testing the Collatz conjecture…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Accessing dict_keys element by index in Python3
  • Change column type in pandas
  • Making a map of composite types typescript
  • I'm trying to use a stored procedure or function…
  • How to create multiple object of same data class kotlin
  • How to use java.net.URLConnection to fire and handle…
  • Use of Jquery on scroll event
  • How do I deal with installing peer dependencies in…
  • Smart way to truncate long strings
  • Binance WebSocket Order Book - depths change every time
  • Scraping Tables in Python Using Beautiful Soup…
  • jQuery .each() index?
  • Fix top buttons on scroll of list below
  • Polymer 1.0: Sorting iron-list
  • Argument Exception "Item with Same Key has already…
  • How do you divide each element in a list by an int?
  • How can I access and process nested objects, arrays or JSON?
  • Why does "return list.sort()" return None, not the list?
  • C compile : collect2: error: ld returned 1 exit status
  • notifyDataSetChange not working from custom adapter
  • Adding multiple dropdown menu's next to each other…
  • Accessing a mapped list
  • How to make a deep copy of Java ArrayList
  • Python Dictionary Comprehension
  • How do I add items to this shopping list
  • String variable interpolation Java
  • Why does a match on covariant enum does not behave…
  • Dictionary returning a default value if the key does…
  • Fastest way to list all primes below N
  • How to unescape a Java string literal in Java?
  • Google Sheets Script Array Length Returning Null
  • Material-UI button requires 3 clicks before it will…
  • How to filter a RecyclerView with a SearchView
  • React: how to update state.item[1] in state using setState?
  • TypeError: 'dict_keys' object does not support indexing
  • Using CTE in Oracle SQL (ORA-00923: FROM keyword not…
  • Polymer data-binding: how to access data in nested template?
  • LINQ select in C# dictionary
  • Remove similar tuple from dictionary of tuples
  • Creating a 2D list from a 2D list using list comprehension
  • Trying to sequentially divide each number in a list…
  • Max function using divide and conquer approach is…
  • Exponentiation in Python - should I prefer **…
  • Can't install via pip because of egg_info error
  • Case insensitive access for generic dictionary
  • creating a python 2 player game with functions & classes
  • Swift Combine: enqueue updates to one publisher…
  • Android ListView not refreshing after notifyDataSetChanged
  • Are dictionaries ordered in Python 3.6+?
  • Reduce vs Collect method on Parallel Streams vs…
  • Observe property on an array of objects for any changes
  • Correct way to use StringBuilder in SQL
  • Finding whether a point lies inside a rectangle or not
  • how to fix 'Access to XMLHttpRequest has been…
  • Polymer 1.x: Observers
  • Centering in CSS Grid
  • Polymer 1.x: Pre-load element attributes
  • How to remove all ListBox items?
  • Iron-data-table fails to populate data from databinding
  • A couple of problems with instant search and list…
  • ComboBox.SelectedItem giving Null value
  • Python Array with String Indices
  • Best way to convert string to bytes in Python 3?
  • Usage of __slots__?
  • Change the name of a key in dictionary
  • Create a list within a list based on user input
  • Polymer - Set Array Not Updating DOM
  • How do I connect two collections and get data from…
  • Appending to list in Python dictionary
  • Vuex state change on object does not trigger rerender
  • Optimal expression to evaluate condition and set…
  • Generating swagger for Dictionary
  • How to handle Vue 2 memory usage for large data (~50…
  • Route transitions destroy rendered view object;…
  • Animation of each element separately in the v -for…
  • d3.js - draw arrow line from border to border
  • TypeScript metadata reflection references other…
  • Backbone.js backed list not being refreshed by…
  • Vuex - Update an entire array
  • "Thinking in AngularJS" if I have a jQuery background?
  • append multiple values for one key in a dictionary
  • Creating a singleton in Python
  • How to add elements of a string array to a string…
  • Start redis-server with config file
  • How can we load color from a sequential scale into a…
  • How to use Servlets and Ajax?
  • JavaScript card game: set the player who deals the…
  • Android M - check runtime permission - how to…
  • Convert a normal python code to an MPI code
  • How to iterate (keys, values) in JavaScript?
  • JavaScript hashmap equivalent

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to Sort a List by a property in the object

Next Post:

Check if a value is an object in JavaScript

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error