FreeKB - Python (Scripting) Getting Started with Hashes
Python (Scripting) - Getting Started with Hashes

A dictionary creates key:value pairs. For example, let's say you have the following key:value pairs.

Key Value
name Jeremy
id 123456
occupation Engineer


In this example, a variable named dict is created, and the dict variable contains the key:value pairs.

dict = {'name': 'Jeremy', 'id': 123456, 'occupation': 'Engineer'}



You can print the contents of the entire dictionary.

print dict


print dict will print all of the keys and values in the dictionary, like this.

{'name': 'Jeremy', 'id': 123456, 'occupation': 'Engineer'}


Or, you can print the value of a key. For example, the following will print the value "Jeremy" in the "name" key.

print dict['name']


Start with an empty hash

Following will create an empty dictionary (does not contain any key value pairs).

dict = {}


Then, somewhere in the script key:value pairs will be created. In this example, a key called "name" is created with a value of "Jeremy" and another key called "occupation" with a value of "engineer".

dict.update( {'name' : 'Jeremy'} )
dict.update( {'occupation' : 'engineer'} )


You can then print the values associated with a hash key.

print dict['name']
print dict['occupation']



Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter 20e38 in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |