Save a dictionary to a file

Given a dictionary such as:

dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}

We can save it to one of these formats:

  • Comma seperated value file (.csv)
  • Json file (.json)
  • Text file (.txt)
  • Pickle file (.pkl)

You could also write to a SQLite database.

Related Courses:

save dictionary as csv file

we can write it to a file with the csv module.

import csv
 
dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
w = csv.writer(open("output.csv", "w"))
for key, val in dict.items():
w.writerow([key, val])
python-write-dictionary-to-csv
The dictionary file (csv) can be opened in Google Docs or Excel

save dictionary to json file

If you want to save a dictionary to a json file

 
import json
 
dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
 
json = json.dumps(dict)
f = open("dict.json","w")
f.write(json)
f.close()

save dictionary to text file (raw, .txt)

You can save your dictionary to a text file using the code below:

dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
f = open("dict.txt","w")
f.write( str(dict) )
f.close()

save dictionary to a pickle file (.pkl)

The pickle module may be used to save dictionaries (or other objects) to a file. The module can serialize and deserialize Python objects.

import pickle
dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
f = open("file.pkl","wb")
pickle.dump(dict,f)
f.close()

Log

Log messages can indicate an event has executed.
You can use logging for these purposes:

  • debugging
  • informational messages
  • show warnings
  • show errors
  • show critical messages

The log method to use depends on the severity of the message. Debug messages can help you with programming your applications but are not severe.

Overview:

To use start logging, load the logging module with “import logging”.

import logging
logging.warning('File could not be opened')

We can use all the types of logging:

import logging
logging.debug('Debug message')
logging.info('Informational message')
logging.warning('Warning message')
logging.error('Error mesage')
logging.critical('Critical message')

Logging levels

You can add debug messages to your program, and on release change the logging level to information to hide them. It’s also recommended to save logging messages to a file:

logging.basicConfig(filename='program.log',level=logging.INFO)

To return to debugging mode, change to:

logging.basicConfig(filename='program.log',level=logging.DEBUG)

The standard level is warning.

Practical example

An example of using the log module below:

import logging
 
x = int(raw_input("Enter a number: "))
 
if x < 0:
    logging.error('Error: x must be positive.')
    exit(0)
else:
    print("Starting calculation")
    logging.info("Calculation started.")

 

Array find

Arrays are usually referred to as lists. For convience, lets call them arrays in this article.

Python has a method to search for an element in an array, known as index(). 
We can find an index using:

x = ['p','y','t','h','o','n']
print(x.index('o'))

Arrays start with the index zero (0) in Python:

python-string
Python character array

If you would run x.index(‘p’) you would get zero as output (first index).

Array duplicates: If the array contains duplicates, the index() method will only return the first element.

Find multiple occurences

If you want multiple to find multiple occurrences of an element, use the lambda function below.

get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]

Find in string arrays

To find an element in a string array use:

x = ["Moon","Earth","Jupiter"]
print(x.index("Earth"))

You could use this code if you want to find multiple occurrences:

 
x = ["Moon","Earth","Jupiter","Neptune","Earth","Venus"]
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print(get_indexes("Earth",x))

Find in numeric array

The index method works on numeric arrays too:

x = [5,1,7,0,3,4]
print(x.index(7))

To find multiple occurrences you can use this lambda function:

 
x = [5,1,7,0,3,4,5,3,2,6,7,3,6]
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print(get_indexes(7,x))

Round number

The round(x,n) method returns a rounded number x to n decimals.
The arguments:

  • x : number to round
  • n : number of decimals
#!/usr/bin/python
 
x = round(1.5056, 2)
print(x)

which would return 1.06

Rounding errors

 
You would probably round 1.85, 2.85, 3.85, 4.85 and 5.85 up, right? If you try this in a computer you won’t get that result:

print( round(1.85, 1) )
print( round(2.85, 1) )
print( round(3.85, 1) )
print( round(4.85, 1) )
print( round(5.85, 1) )
print( round(6.85, 1) )

Decimal places are not exact in a computer system, which uses base 2 instead of base 10. You can view the value that round returns with the Decimal module:

#!/usr/bin/python
from decimal import Decimal
 
print( Decimal(1.85) )
print( Decimal(2.85) )
print( Decimal(3.85) )
print( Decimal(4.85) )
print( Decimal(5.85) )
print( Decimal(6.85) )

It will print the values that are stored in the computer memory. You might be surprised. These numbers are called floating points.

Round to the nearest number

 
Round up
If you want all floating points to be rounded up, use the math.ceil(x) method instead:

#!/usr/bin/python
import math
 
print( math.ceil(2.5) )

Round down
If you want a floating point to be rounded down, you could use

#!/usr/bin/python
import math
 
print( math.floor(2.5) )

 

Sleep

To make a Python program delay (pause execution), use the sleep(seconds) method.  which can be found in the time module. time.sleep pauses execution, if you don’t want that use threading instead.

import time
time.sleep(5) # Wait for 5 seconds

The time.sleep(sec) method supports floating point numbers, meaning you can make it wait half a second too

import time
time.sleep(0.100) # Wait for 100 milliseconds

A simple countdown timer from 5:

import time
 
seconds = 5
while seconds > 0:
    print(seconds)
    time.sleep(1)
    seconds = seconds - 1

Accuracy

The time.sleep(seconds) is not real time. The accuracy depends on the operating system, sometimes it may be off in terms of milliseconds.

To wait about 50 milliseconds:

Python 2.7.11+ (default, Apr 17 2016, 14:00:29) 
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from time import sleep
>>> sleep(0.05)

You won’t get exactly 50ms if you rely on the sleep method.

Most PC machines have hardware limits in the 1-10ms range, regardless of operating system. To the operating system, time.sleep() just means a hint. It’s not a good timing mechanism, but good enough for most applications.

Operating systems may have different implementations, causing a difference in time.

time.sleep accuracy
(Image from Stackoverflow)

For higher accuracy, you need dedicated hardware (embedded system) to keep accurate time on the milliseconds level.

Speech engines with python tutorial

Text To Speech (TTS)
Text To Speech (TTS)
A computer system used to create artificial speech is called a speech synthesizer, and can be implemented in software or hardware products.

A text-to-speech (TTS) system converts normal language text into speech. How can we use speech synthesis in Python?

Related courses:

Pyttsx

Pyttsx is a cross-platform speech (Mac OSX, Windows, and Linux) library. You can set voice metadata such as age, gender, id, language and name. Thee speech engine comes with a large amount of voices.

Text to speech sample:
 

Install with:

sudo pip install pyttsx

Create the code speech1.py

import pyttsx
engine = pyttsx.init()
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()

And execute it with python.

Espeak

eSpeak is a compact open source software speech synthesizer for English and other languages, for Linux and Windows.

Text to speech sample:
 

We can install using:

sudo apt-get install espeak

Create the code speech2.py:

import os
os.system("espeak 'The quick brown fox'")

It is very easy to use, but like pyttsx it sounds very robotic.

gTTS

The gtts module no longer works.

I found a script on Github that uses the Google speech engine. The script comes with many options and does not speak, instead it saves to an mp3. We added a command to play the mp3 automatically:

os.system("mpg321 out.mp3 -quiet")

Run with:

python gtts.py -s 'Python programming example'

The voice is extremely natural. The only disadvantage is that you need to be connected with the Internet when running this script.

Links

You might like:

Posts navigation

1 2