Python Dictionary Tutorials

Dictionary is an important part of Python. It is built around dictionaries, be it modules, classes, objects, globals(), or locals().

Iterate Through a Dictionary

d = {'name': 'TL Templates', 'url': 'https://tltemplates.com/', 'category': 'programming'}
# python 3
for key, value in d.items():
    print(key + value)
# python 2
for key, value in d.iteritems():
    print key + value

Check whether given key already exists in a dictionary

Here are several ways to check for a key’s existence based on Python version (2 or 3):

d = {'name': 'TL Templates', 'url': 'https://tltemplates.com/', 'category': 'programming'}
# python 3
if 'category' in d:
    print(d['category'])
# python 3
if 'category' in d.keys():
    print(d['category'])
# python 2
if d.has_key('category'): 
    print d['category']

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close