Python
Using Dictionaries in Python
- Details
- Written by: Erich Forler
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?
- Details
- Written by: Erich Forler
On a Raspberry Pi (and probably other Debian-based systems) the available python modules are found in /usr/lib/python3/dist-packages.
Classes in Python
- Details
- Written by: Erich Forler
This video series is a quick moving and concise explanation of creating classes in Python
Introduction to classes https://youtu.be/ZDa-Z5JzLYM
Class Variables https://youtu.be/BJ-VvGyQxho
Sub Classes https://youtu.be/RSl87lqOXDE
Formating output in Python
- Details
- Written by: Erich Forler
This is just a tidbit about formatting output from Python.
'{} {}'.format(self.first, self.last) would give you "Erich Forler".