
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'])
Did you find this article helpful?
If so, consider buying me a coffee over at