Python Dictionary keys() - Example

[Pages:3]Python Dictionary keys()

Python Dictionary keys()

Python Dictionary keys() method returns a new view object containing dictionary's keys. This view object presents dynamic data, which means if any update happens to the dictionary, the view object reflects those changes. The view object returned by keys() is of type dict_keys. View objects support iteration and membership checks. So, we can iterate over the keys, and also check if a key is present or not using membership test. In this tutorial, we will learn the syntax of dict.keys() method and go through examples covering different scenarios with keys() method.

Syntax ? keys()

The syntax of dict.keys() is dict.keys()

keys() method returns object of type dict_keys.

Example 1 ? Python dict.keys() ? Iteration

In this example, we will iterate over the dictionary keys using dict.keys() iterable. Python Program dictionary = {'a': 58, 'b': 61, 'c': 39} for key in dictionary.keys():

print(key)

Program Output a b c

Example 2 ? Python dict.keys() ? Checking if Key is Present

In this example, we will use dict.keys() to check if key is present in dictionary or not. Python Program

dictionary = {'a': 58, 'b': 61, 'c': 39} key = 'b' if key in dictionary.keys():

print('Key present in dictionary.') else:

print('Key not present in dictionary.')

Program Output

Key present in dictionary.

As the key is present in the dictionary, the expression key in dict.keys() returned True.

Conclusion

In this Python Tutorial, we learned about Python Dictionary method dict.keys(). We have gone through the syntax of keys(), and its usage with example programs.

Python Programming

Python Tutorial Install Python Install Anaconda Python Python HelloWorld Program Python Variables Python Variable Data Type Conversion Python Comments

Control Statements

Python If Python If Else Python While Loop Python For Loop

Python String

Python String Methods Python String Length Python String Replace Python Split String Python Count Occurrences of Sub-String Python Sort List of Strings

Functions

Python Functions

Python Collections

Python List Python Dictionary

Advanced

Python Multithreading

Useful Resources

Python Interview Questions

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download