How do you get a list of all the keys in a dictionary?

Python | Get dictionary keys as a list

Given a dictionary, write a Python program to get the dictionary keys as a list.

Examples:

Input : {1:'a', 2:'b', 3:'c'} Output : [1, 2, 3] Input : {'A' : 'ant', 'B' : 'ball'} Output : ['A', 'B']

Approach #1 : Using dict.keys() [For Python 2.x]




# Python program to get

# dictionary keys as list

def getList(dict):

return dict.keys()

# Driver program

dict = {1:'Geeks', 2:'for', 3:'geeks'}

print(getList(dict))

Output:


[1, 2, 3]


Approach #2 : Naive approach.




# Python program to get

# dictionary keys as list

def getList(dict):

list = []

for key in dict.keys():

list.append(key)

return list

# Driver program

dict = {1:'Geeks', 2:'for', 3:'geeks'}

print(getList(dict))

Output: [1, 2, 3]


Approach #3 : Typecasting to list




# Python program to get

# dictionary keys as list

def getList(dict):

return list(dict.keys())

# Driver program

dict = {1:'Geeks', 2:'for', 3:'geeks'}

print(getList(dict))

Output: [1, 2, 3]


Approach #4 : Unpacking with *
Unpacking with * works with any object that is iterable and, since dictionaries return their keys when iterated through, you can easily create a list by using it within a list literal.




# Python program to get

# dictionary keys as list

def getList(dict):

return [*dict]

# Driver program

dict = {'a': 'Geeks', 'b': 'For', 'c': 'geeks'}

print(getList(dict))

Output: ['c', 'a', 'b']


Approach #5 : Using itemgetter
itemgetter from operator module return a callable object that fetches item from its operand using the operand’s __getitem__() method. This method is then mapped to dict.items() and them typecasted to list.




# Python program to get

# dictionary keys as list

from operator import itemgetter

def getList(dict):

return list(map(itemgetter(0), dict.items()))

# Driver program

dict = {'a': 'Geeks', 'b': 'For', 'c': 'geeks'}

print(getList(dict))

Output: ['b', 'a', 'c']

How do you get a list of all the keys in a dictionary?




Article Tags :

Python

Python Programs

Python dictionary-programs

python-dict

Practice Tags :

python-dict

Creating a list of all keys in dictionary using dict.keys()

In python, dictionary class provides a member function i.e.

dict.keys()
It returns a view object or iterator to the list of all keys in dictionary.We can use this object for iteration or creating new list.Let’s use that to get the list of all keys in the above dictionary.
# Create a new list from the view object returned by keys() dictkeys = list (wordFreqDic.keys())
dictkeys content will be,
['city', 'test', 'at', 'Hello', 'this', 'here']

Dict Hash Table

Python's efficient key/value hash table structure is called a "dict". The contents of a dict can be written as a series of key:value pairs within braces { }, e.g. dict = {key1:value1, key2:value2, ... }. The "empty dict" is just an empty pair of curly braces {}.

Looking up or setting a value in a dict uses square brackets, e.g. dict['foo'] looks up the value under the key 'foo'. Strings, numbers, and tuples work as keys, and any type can be a value. Other types may or may not work correctly as keys (strings and tuples work cleanly since they are immutable). Looking up a value which is not in the dict throws a KeyError -- use "in" to check if the key is in the dict, or use dict.get(key) which returns the value or None if the key is not present (or get(key, not-found) allows you to specify what value to return in the not-found case).

## Can build up a dict by starting with the the empty dict {} ## and storing key/value pairs into the dict like this: ## dict[key] = value-for-that-key dict = {} dict['a'] = 'alpha' dict['g'] = 'gamma' dict['o'] = 'omega' print dict ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'} print dict['a'] ## Simple lookup, returns 'alpha' dict['a'] = 6 ## Put new key/value into dict 'a' in dict ## True ## print dict['z'] ## Throws KeyError if 'z' in dict: print dict['z'] ## Avoid KeyError print dict.get('z') ## None (instead of KeyError)

How do you get a list of all the keys in a dictionary?

A for loop on a dictionary iterates over its keys by default. The keys will appear in an arbitrary order. The methods dict.keys() and dict.values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary. All of these lists can be passed to the sorted() function.

## By default, iterating over a dict iterates over its keys. ## Note that the keys are in a random order. for key in dict: print key ## prints a g o ## Exactly the same as above for key in dict.keys(): print key ## Get the .keys() list: print dict.keys() ## ['a', 'o', 'g'] ## Likewise, there's a .values() list of values print dict.values() ## ['alpha', 'omega', 'gamma'] ## Common case -- loop over the keys in sorted order, ## accessing each key/value for key in sorted(dict.keys()): print key, dict[key] ## .items() is the dict expressed as (key, value) tuples print dict.items() ## [('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')] ## This loop syntax accesses the whole dict by looping ## over the .items() tuple list, accessing one (key, value) ## pair on each iteration. for k, v in dict.items(): print k, '>', v ## a > alpha o > omega g > gamma

There are "iter" variants of these methods called iterkeys(), itervalues() and iteritems() which avoid the cost of constructing the whole list -- a performance win if the data is huge. However, I generally prefer the plain keys() and values() methods with their sensible names. In Python 3 revision, the need for the iterkeys() variants is going away.

Strategy note: from a performance point of view, the dictionary is one of your greatest tools, and you should use it where you can as an easy way to organize data. For example, you might read a log file where each line begins with an IP address, and store the data into a dict using the IP address as the key, and the list of lines where it appears as the value. Once you've read in the whole file, you can look up any IP address and instantly see its list of lines. The dictionary takes in scattered data and makes it into something coherent.

Python Dictionary keys()

The Python dictionary keys() method returns all the keys in a dictionary. This method returns keys as a special object over which you can iterate. keys() accepts no arguments.

The syntax for the keys() method is:

dict_name.keys()

We add the keys() method after the dictionary name.

The keys() method returns a view object rather than a list of keys. This object is iterable so you can view its contents using a for statement. But, it may be necessary to convert this object to a list.

81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.

Find Your Bootcamp Match

The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.

Start your career switch today

Suppose you want to print all the keys in the dictionary to the console. You should convert the keys to a list to make the output more readable:

key_list = list(dictionary.keys()) print(key_list)

This code returns a list of keys. We know our data is in a list because the values are enclosed within square brackets.

Alternatively, say you want to find out the first key in the dictionary. You can do this using indexing. But, you would first need to convert the collection of keys to a list:

key_list = list(dictionary.keys()) print(key_list[0])

This code finds the key at the index position 0 in the list of dict keys.

» MORE: Python TypeError: builtin_function_or_method is not iterable Solution

How to get Dictionary keys as a List in Python?

Posted in Programming LAST UPDATED: SEPTEMBER 1, 2021

Table of Contents

In Python 2.x version, this was easy because the function dict.keys() by default returned a list of keys of the dictionary but that is not the case with Python 3.x version.

In Python 3.x if we use this code, the dict.keys()function returns a dictionary view object which acts as a set.

newdict = {1:0, 2:0, 3:0} print(newdict.keys())

Output:

dict_keys([1, 2, 3])

So this won't work in Python 3.x version but there are many other ways to get dictionary keys in a list.