Python Dictionary keys: The Complete Guide

0
31
Python Dictionary Keys example tutorial Example

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

Python Dictionary keys

The dictionary keys() is a built-in Python function that returns the view object. That view object contains keys of the dictionary as a list. The dictionary keys() method returns the list of all the available keys in the dictionary.

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

The keys() don’t take any parameters. Therefore, 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’s 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 empty the dictionary, the keys 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 dictionary elements as we can for the list. Without the use of keys(), no other mechanism provides means to access dictionary keys as the list by index.

How do keys() work 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

When the dictionary is updated, keys are automatically updated to reflect changes.

That’s it for this tutorial.

Related Posts

Python Dictionary fromKeys()

Python dictionary pop()

Python dictionary copy()

Python dict to json

Leave A Reply

Please enter your comment!
Please enter your name here

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