Python return all keys

Python Get Dictionary Keys as a List

How to get Python Dictionary Keys as a List? To get all dictionary keys as a list in Python use the keys() method and covert the returned object to a list using list(). We can also get keys from a dictionary using various ways in Python. In dictionaries, elements are presented in the form of key : value pairs and all keys are associated with their corresponding values.

  1. list(dict.keys()) returns the dictionary keys as a list.
  2. You can use for loop to iterate the dictionary and get the key from each iteration.
  3. Use a list comprehension to get all keys from the dictionary.
  4. Finally use map() with lambda to get all keys.

1. Quick Examples of Dictionary Keys as a List

Following are quick examples of getting dictionary keys as a list in Python.

 # Below are the quick examples # Example 1: Get the keys of dictionary as a list # using .keys() & list() keys = list(my_dict.keys()) # Example 2: Get the keys using for loop mylist = [] for key in my_dict.keys(): mylist.append(key) # Example 3: Get the keys as a list using dictionary comprehension keys = Python return all keys # Example 4: Use map and lambda get the keys of dict mykeys = list(map(lambda x: x[0], my_dict.items())) # Example 5: Using * operator get the keys print([*my_dict]) 

2. What is Python Dictionary

A Python dictionary is a key-value collection that is unordered, mutable, and does not allow duplicate keys. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with <> and key: value pair separated by commas. The dictionaries are indexed by keys.

Dictionaries are mutable hence, you can be added, deleted, and updated their key:value pairs. keys are an immutable type such as string, numbers(int, float), and tuple. In case, you add duplicates, it will update the existing key with the new value. Let’s create a Python dictionary,

 # Create dictionary my_dict = print(my_dict) 

python dictionary keys as list

3. Python Get Dictionary keys as a List

To get dictionary keys as a list in Python use the dict.keys() which returns the keys in the form of dict_keys() and use this as an argument to the list() . The list() function takes the dict_keys as an argument and converts it to a list, this will return all keys of the dictionary in the form of a list. Here, is an example.

 # Get the keys of dictionary as a list # my_dict.keys() print(my_dict.keys()) # type print(type(my_dict.keys())) # Convert to list keys = list(my_dict.keys()) print(keys) # Output: #dict_keys(['course', 'fee', 'duration', 'discount']) # # ['course', 'fee', 'duration', 'discount'] 

4. Get Keys as a List using Looping

Use for loop to iterate a python dictionary over keys, by default when you use for loop with dict, it returns a key from the dict for each iteration, add the key to the list to get all keys as a list.

 # Get the keys using for loop mylist = [] for key in my_dict.keys(): mylist.append(key) print(mylist) # Output: ['course', 'fee', 'duration', 'discount'] 

5. Get Keys using List Comprehension

Alternatively, using list comprehension we can get all the keys of the Python dictionary. Let’s use list comprehension(a concise way of creating a new list) and get the list of all keys.

 # Get the keys as a list using dictionary comprehension keys = Python return all keys print(keys) # Output # ['course', 'fee', 'duration', 'discount'] 

6. Get Keys as a List using Map and lambda

We can also get the keys as a list using another approach i.e. the combination of a map() function and a lambda function. Let’s use both functions and get our desired output.

 # Use map and lambda to get the keys of dict myList = list(map(lambda x: x[0], my_dict.items())) print(myList) # Output: # ['course', 'fee', 'duration', 'discount'] 

Here, lambda expression is called for each item in the dictionary and x[0] gives you a key from each item.

Читайте также:  Creating wordpress plugins php

7. Using Unpacking operator(*) & Get the Keys

Using the unpacking operator ‘*’ we can get the all keys from the Python dictionary. This operator works with any iterable object and returns a list. Let’s apply ‘*’ operator on the given dictionary.

 # Using * operator get the keys print([*my_dict]) # Output: # ['course', 'fee', 'duration', 'discount'] 

8. Conclusion

In this article, I have explained how to get a python dictionary keys as a list. You can achieve this in several ways, for example, using list(dict.keys), using map() with lambda, and list comprehension.

References

You may also like reading:

Источник

Return Keys, Values, or Key/Value Pairs¶

The structure of a Python dictionary involves pairs of items. Each element in the collection contains a key and a value.

Python provides two methods that allow us to access all of the keys (without their values), or all of the values (without their keys).

Return All Keys¶

The general syntax for the keys() method is:

No arguments are needed inside the parentheses, and the method returns an object that contains all of the keys in the dictionary.

Let’s explore what this means.

Print the object returned by the keys() method:

phone_book =  'Mom' : '555-5555', 'Work' : '555-5556', 'Home' : '123-456-7890', 'BFF' : '555-5557' > book_keys = phone_book.keys() print(book_keys) print(type(book_keys)) 

Console Output

dict_keys([‘Mom’, ‘Work’, ‘Home’, ‘BFF’])

Notice that when we print book_keys , we see something that looks like a list, but that list is enclosed in dict_keys() . Line 10 shows us that book_keys is a data type that we have not seen before— dict_keys .

Good news! We do not need a deep understanding of the dict_keys data type. We just need to know how to use it. One option is to use the list() function to convert the dict_keys object into a list.

book_keys = list(phone_book.keys()) print(book_keys) print(type(book_keys)) print(book_keys[0]) 

Console Output

In the dictionary iteration section, we see how to apply the keys() method to loop through a dictionary.

Return All Values¶

The general syntax for the values() method is:

No arguments are needed inside the parentheses, and the method returns an object that contains all of the values from the dictionary.

phone_book =  'Mom' : '555-5555', 'Work' : '555-5556', 'Home' : '123-456-7890', 'BFF' : '555-5557' > book_values = phone_book.values() print(book_values) print(type(book_values)) print(list(book_values)) 

Console Output

dict_values(['555-5555', '555-5556', '123-456-7890', '555-5557']) ['555-5555', '555-5556', '123-456-7890', '555-5557']

By collecting all of the values from a dictionary into one object, we can loop through the entries or search the object for a specific value.

Return All Key/Value Pairs¶

The general syntax for the items() method is:

No arguments are needed inside the parentheses, and the method returns an object that contains all of the key/value pairs from the dictionary.

Just like with keys() and values() , we can convert the object into a list.

phone_book =  'Mom' : '555-5555', 'Work' : '555-5556', 'Home' : '123-456-7890', 'BFF' : '555-5557' > book_items = list(phone_book.items()) print(book_items) print(book_items[0]) print(book_items[0][0], book_items[0][1]) 

Console Output

[('Mom', '555-5555'), ('Work', '555-5556'), ('Home', '123-456-7890'), ('BFF', '555-5557')] ('Mom', '555-5555') Mom 555-5555

Note that each element in the list comes is a pair, which can be accessed with bracket notation. A single bracket, like book_items[0] , accesses one pair in the list. A pair of brackets, like book_items[1][0] lets us access one half of a pair.

Why?¶

When we define the keys(), values() , and items() methods on their own, it might be difficult to see why they are so important. This is especially true when we throw in the returns an object business.

To fully understand why these dictionary methods are helpful, we must use them in concrete examples. If you haven’t done so, read the dictionary iteration section and then return to this appendix page.

Источник

Get All Keys from Dictionary in Python

To get all keys from Dictionary in Python use the keys() method, which returns all keys from the dictionary as a dict_key(). we can also get all keys from a dictionary using various ways in Python. In dictionaries, elements are presented in the form of key : value pairs and all keys are associated with their corresponding values.

  1. dict.keys() returns the key in the form of dict_keys([comma separated keys])
  2. list(dict.keys()) returns the keys as a list.
  3. You can use for loop to iterate the dictionary and get the key from each iteration.
  4. Use a list comprehension to get all keys from the dictionary.
  5. Finally use map() with lambda to get all keys.

1. Quick Examples of Getting All Dictionary Keys

Following are quick examples of getting all dictionary keys in Python.

 # Below are the quick examples # Example 1: Get the keys of dictionary # using .keys() keys = my_dict.keys() # Example 2: Get the keys of dictionary # using .keys() & list() keys = list(my_dict.keys()) # Example 3: Get the keys using for loop for key in my_dict.keys(): # Example 4: Get the keys using dictionary comprehension keys = Python return all keys # Example 5: Use map and lambda get the keys of dict print(list(map(lambda x: x[0], my_dict.items()))) # Example 6: Using * operator get the keys print([*my_dict]) # Example 7: Get the specified key based on value keys = Python return all keys 

2. What is Python Dictionary

A Python dictionary is a key-value collection that is unordered, mutable, and does not allow duplicate keys. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with <> and key: value pair separated by commas. The dictionaries are indexed by keys.

Dictionaries are mutable hence, you can be added, deleted, and updated their key:value pairs. keys are an immutable type such as string, numbers(int, float), and tuple. In case, you add duplicates, it will update the existing key with the new value. Let’s create a Python dictionary,

 # Create dictionary my_dict = print(my_dict) 

python dictionary get all keys

3. Get All Dictionary Keys using dict.keys()

Using dict.keys() method in Python we can get the all keys from the dictionary in the form view object where the order of keys in a list is the same as the insertion order. Let’s call the keys() function on the above-created dictionary.

 # Get the keys from dictionary keys = my_dict.keys() print(keys) 

python dictionary get all keys

If you want to get all the keys in the dictionary in the form of a list use the dict.keys() as an argument to the list() . The list() function takes the dict_keys as an argument and convert it to a list, this will return all keys of the dictionary in the form of a list.

 # Get the keys of dictionary as a list # using .keys() & list() keys = list(my_dict.keys()) print(keys) # Output: # ['course', 'fee', 'duration', 'discount'] 

4. Get Dictionary Keys using for Loop

Use for loop to iterate a python dictionary over keys, by default when you use for loop with dict, it returns a key from the dict for each iteration. For example,

 # Get the keys using for loop for key in my_dict.keys(): print(key) # Output: # course # fee # duration # discount 

If you wanted to get all keys as a list, use the below example.

 # Get the keys using for loop mylist = [] for key in my_dict.keys(): mylist.append(key) print(mylist) 

5. Get Dictionary Keys using Comprehension

Alternatively, using comprehension we can get all the keys of the Python dictionary. Let’s use comprehension(a concise way of creating a new list) and get all keys of the dictionary.

 # Get the keys as a list using dictionary comprehension keys = Python return all keys print(keys) # Output # ['course', 'fee', 'duration', 'discount'] 

6. Get Keys using Map and lambda

We can also get the dictionary keys using another approach i.e. the combination of a map() function and a lambda function. Let’s use both functions and get our desired output.

 # Use map and lambda to get the keys of dict print(list(map(lambda x: x[0], my_dict.items()))) # Output: # ['course', 'fee', 'duration', 'discount'] 

7. Using Unpacking operator(*) & Get the Keys

Using the unpacking operator ‘*’ we can get the all keys from the Python dictionary. This operator works with any iterable object and returns a list. Let’s apply ‘*’ operator on the given dictionary.

 # Using * operator get the keys print([*my_dict]) # Output: # ['course', 'fee', 'duration', 'discount'] 

8. Get Key Based on Value in Python

As you know the dictionary keys are associated with their corresponding values. We can get specified keys of a dictionary based on their corresponding value using list comprehension. For example,

 # Get the specified key based on value keys = Python return all keys print(keys) # Output: # ['course'] 

9. Conclusion

In this Python article, I have explained how to get all keys from the python dictionary using dict.keys() method. Also explained getting keys using map() with lambda, list comprehension, and many other ways.

References

You may also like reading:

Источник

Оцените статью