Labels

Arduino (1) Bugs (3) C (1) Install (3) Linux (25) Maths (1) Python (11) Raspberry Pi (4)

Saturday, 6 February 2016

How to create a Python Dictionary.

Dictionaries in python are quite similar to arrays in how they look however arrays are indexed by a range of numbers i.e. 1-10, but dictionaries are indexed by their key.You can set these keys to immutable data types only.They can also be known as key pair arrays.

You will used to seeing this to create a standard array using square brackets.
test_array = []


If you want to create a dictionary you use curly brackets.
test_dictionary = {}


The format of a dictionary looks like this.
{'TEST': 1}

With TEST being the key and 1 the pair.

If you want to store values in a dictionary
test_dictionary["KEY"] = "Pair"

Note: You don't have to just use string other data types in place of each one.

To iterate through a dictionary
for key, value in test_dictionary.items():
     print('{0} links to {1}'.format(key, value)
Note: Using format when printing strings is considered good practice.