Using Dictionaries in Python

Python has five standard data types −

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

You can only print strings.

You can convert other variable types to string by using str() function

enumerate() instead of using index.

Example:

List

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

Tuples

Tuples are like lists but us round brackets and can be though of as read only lists.

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )

Dictionary 

Dictionary is an associative array

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

To retrieve the data from the dictionary, you can use either of these two approaches:

tinydict['name']

tinydict.get('name', 'Not Found') # this method is cleaner at handling error conditions. It returns Not found if the 'name' doesn't exist

Looping through a dictionary for key and value

for key, value in tinydict.items()

example

for char in english_word :
    for key, value in letters_list.items() :
        if value == char :

Where are the Python Modules?

On a Raspberry Pi (and probably other Debian-based systems) the available python modules are found in /usr/lib/python3/dist-packages.

 

Formating output in Python

This is just a tidbit about formatting output from Python.

'{} {}'.format(self.first, self.last) would give you "Erich Forler".