Linux (28) Python (13) Raspberry Pi (5) Bugs (3) Install (3) C (2) Brainf**k (1) HTML (1) Maths (1) Sorts (1)

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.

No comments:

Post a comment