AppDividend
Latest Code Tutorials

Python Dictionary Keys Example | Python dict keys()

0

Python dictionary keys() is an inbuilt function that returns the view object. That view object contains keys of the dictionary, as a list. Python dictionary method keys() returns the list of all the available keys in the dictionary.

Python Dictionary Keys

Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds the key: value pair.

Python keys() method returns a view object. The view object contains the keys of the dictionary, as a list. The view object will reflect any changes done to the dictionary.

The keys() doesn’t take any parameters. When the dictionary is changed, the view object also reflects these changes. The syntax for the Dictionary keys() method is the following.

dictionary.keys()

Let see the following example.

# app.py

dict = { 
    'shopping': 'flipkart',
    'transport': 'ola',
    'banking': 'paytm',
    'hotel': 'oyo rooms'
 }
dictKeys = dict.keys()
print(dictKeys)

The output is the following.

Python Dictionary Keys Example | Keys() Method Tutorial

Now, if you emptied the dictionary, then the keys also get emptied.

# app.py

dict = { 
    'shopping': 'flipkart',
    'transport': 'ola',
    'banking': 'paytm',
    'hotel': 'oyo rooms'
 }
dictKeys = dict.keys()
print(dictKeys)

dict = {}
dictKeys = dict.keys()
print(dictKeys)

See the output below.

Python Dictionary Keys Example Tutorial

The keys() can be used to access the elements of the dictionary as we can do for the list, without the use of keys(), no other mechanism provides means to access dictionary keys as the list by index.

How keys() works when a dictionary is updated?

# app.py

share = {'app': 'Facebook', 'price': 200, }

print('Before dictionary is updated')
keys = share.keys()
print(keys)

# adding an element to the dictionary
share.update({'symbol': 'FB'})
print('\nAfter dictionary is updated')
print(keys)

 See the output.

➜  pyt python3 app.py
Before dictionary is updated
dict_keys(['app', 'price'])

After dictionary is updated
dict_keys(['app', 'price', 'symbol'])
➜  pyt

 Here, when the dictionary is updated, keys are also automatically updated to reflect changes.

Finally, Python Dictionary Keys Example Tutorial is over.

Related Posts

Python Dictionary fromKeys()

Python dict()

Python dictionary pop()

Python dictionary copy()

Python dict to json

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.