Python get all keys in dict python

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 get all keys in dict python # 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 get all keys in dict python 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.

Читайте также:  Символьный тип переменных в питоне

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:

Источник

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 get all keys in dict python # 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 get all keys in dict python 

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.

Читайте также:  No java runtime present requesting install

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 get all keys in dict python 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 get all keys in dict python 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.

Читайте также:  Windows no php ini file

References

You may also like reading:

Источник

Get Keys of a Python Dictionary – With Examples

In this tutorial, we will look at how to get the keys of a Python dictionary with the help of some examples.

How to get the keys of a dictionary in Python?

Get keys of a python dictionary

You can use the Python dictionary keys() function to get all the keys in a Python dictionary. The following is the syntax:

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

# get all the keys in a dictionary sample_dict.keys()

It returns a dict_keys object containing the keys of the dictionary. This object is iterable, that is, you can use it to iterate through the keys in the dictionary. You can use the list() function to convert this object into a list.

Let’s look at some examples.

Using dictionary keys() method

Let’s create a dictionary containing the names to department mappings of employees at an office. The keys here are the employee names whereas the values are their respective departments.

Let’s get all the keys in the dictionary using the dictionary’s keys() function.

# create a dictionary employees = < "Jim": "Sales", "Dwight": "Sales", "Angela": "Accounting" ># get keys of dictionary print(employees.keys())
dict_keys(['Jim', 'Dwight', 'Angela'])

You can see that we get all the names of the employees (the keys in the dictionary employee ) in a dict_keys object.

Now, you can also convert this object to a list using the Python built-in list() function.

# dictionary keys as list print(list(employees.keys()))

We now have the keys in the dictionary employees as a list.

Using Iteration

Alternatively, you can iterate through the dictionary items and append the key in each iteration to a result list.

# create a dictionary employees = < "Jim": "Sales", "Dwight": "Sales", "Angela": "Accounting" ># get keys of dictionary keys_ls = [] for key, val in employees.items(): keys_ls.append(key) print(keys_ls)

We get the keys in the dictionary as a list.

You can also reduce the above computation to a single line using list comprehension.

# get keys of dictionary keys_ls = Python get all keys in dict python print(keys_ls)

We get the same result as above.

In this tutorial, we looked at different ways to get all the keys in a Python dictionary. Using the dictionary’s keys() function is a simpler and a direct way of getting the keys as compared to the iteration based methods.

You might also be interested in –

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

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