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])
{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])
