Mastery 27. Creation and use of Dictionaries

Dictionaries are another helpful data built into python.

Unlike other data types which are indexed by range of numbers, dictionaries are indexed by keys, which can be any immutable value, such as strings, numbers or even tuples (Lists wouln’d work for keys because they can always be changed).

The syntax for a dictionary is the following:

>>Dict={‘key1’=value1, ‘key2’=value2, ‘key3’=value3}

If we wanted to add a new value into the dictionary, we have to add it by entering a new key, for example:

>>Dict[‘key4’]= value4

And we would assume that this new value is added to the end of the dictionary, but unfortunately this wont happen, but it doesnt matter, because even if this new value is stored randomly into the dictionary we can always find it by his key.

For example, if we want to print value3, we type the following:

>>print (Dict[‘key3’])

and as ‘key3’ is the key for value3, value3 will get printed.

In the same way we can modify the value of a key and we can even add as many values we want for only one key by adding a list as the value of the refered key. For example, if we wanted to modify the value of ‘key1’ for a list containing 3 values, the syntax would be the following:

>>Dict[‘key1’]=[val0,val1,val2]

And if we wanted to acces specifically to the second value of a given key (key1, for example), the syntax would be the following:

>>print (Dict[‘key1’][1])

Also we can add a dictionary as the value of the key of a main dictionary, it is just matter of the needs of your program.

If you want to learn more about dictionaries, you can go to this link: https://docs.python.org/2/tutorial/datastructures.html

 

CC BY 4.0 Mastery 27. Creation and use of Dictionaries by Manuel Madrigal is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.