January 12, 2020

Python tutorial 18 | Dictionaries

Moving on to the next tutorial in the Python Tutorials for Beginners. This Python beginner tutorial explains the dictionary data structure. Please view the Python video tutorial 18 or read on... What is dictionary in Python programming? It is a group of key value pairs, that may be stored in any order. The Python dictionary keys can be strings or numbers (immutable data types only). Also, each dictionary key is unique. Python dictionaries are mutable, meaning that any dictionary item may be updated. In other programming languages, dictionaries may be called associative arrays. The dictionary syntax is:

{key0:value0, key1:value1,..., keyn:valuen}

In the above  dictionary format, the key value pairs are separated by commas. The first item is key0:value0, the second item is key1:value1 and so on. The entire group of key value pairs is enclosed within curly braces. Now, let us see Python dictionary examples, Python dictionary operations and Python dictionary functions.

# Python code
num_to_words = {1:'one', 2:'two', 10:'ten', 3:'three', 5:'five'}
# print the Python dictionary (the items may be in any order)
print (num_to_words)
# print the Python dictionary item's value for the given key i.e. print 'three'
print (num_to_words[3])
# modify the Python dictionary item's value for the given key
num_to_words[1] = 'unity'
# print the updated value i.e. print 'unity'
print  (num_to_words[1])

# Python examples of dictionary operations  and dictionary functions
# Python code
# create a Python dictionary
dict = {'a':1000, 'b':2000, 'c':5000}
# print the value for the given key i.e. print 2000
print (dict.get('b'))
# print if the given key exists in the dictionary i.e. print True
print ('c' in dict)
# print if the given key does not exist in the dictionary i.e. print True
print ('d' not in dict)
# print the number of items in the dictionary i.e. print 3
print (len(dict))
# print all the keys of the dictionary i.e. print 'a', 'b' and 'c'
print (dict.keys())
# sorted(dict.keys()) command gives the dictionary keys in alphabetical order
# print only the values of the dictionary i.e. print 1000, 2000 and 5000
print (dict.values())
# print the items (both the keys and their respective values)
print (dict.items())
# use the iter function to loop through the dictionary
for k in iter(dict): print ('The key is ', k, 'and the corresponding value is', dict.get(k))
# delete the item with the given key from the dictionary
del dict['a']
# create a copy of the old dictionary (which now has two items)
dict1 = dict.copy()
# print the two items in the new dictionary
print (dict1.items())
# remove all items from the dictionary
dict.clear()
# print the items in the dictionary i.e. print the now empty dictionary
print (dict.items())

Want to learn more with other Python samples? Please view my Python video tutorial 18. Thank you.

1 comment:

Note: Only a member of this blog may post a comment.