dictionary issue for formatted print

Peter Otten __peter__ at web.de
Sun Nov 9 10:04:20 EST 2014


Yusuf Can Bayrak wrote:

> when dictionary has one value for each key it's okey. I'm just type '%
> greek_letters' and it's working.
> 
> But how can i assign dict's values to formatted print, if it has more
> values than one.
> 
>>
>>    1. # -*- coding: utf-8 -*-
>>    2. greek_letters = {
>>    3.                     'omega': ['ω','Ω'], 'psi': ['ψ', 'Ψ'] , 'kapa':
>>    'κ', 'to': ['τ', 'Τ'], 'lambda': ['λ', 'Λ'],
>>    4.                     'ksi': ['ξ', 'Ξ'], 'delta': ['δ', 'Δ'], 'mu':
>>    ['μ'], 'sigma': ['σ', 'Σ'], 'epsilon': ['ε', 'Ε'],
>>    5.                     'gamma': ['γ', 'Γ'], 'phi': ['φ', 'Φ'],
>>    'theta': ['θ', 'Θ']
>>    6.                 }
>>    7. print 'x(%(to)s) = A * cos(%(omega)s * %(to)s + %(theta)s)' %
>>    greek_letters.values()[1]

You can build a temporary dict:

>>> greek_letters = {
... 'omega': ['ω','Ω'], 'to': ['τ', 'Τ'], 'theta': ['θ', 'Θ']}
>>> print 'x(%(to)s) = A * cos(%(omega)s * %(to)s + %(theta)s)' % {
... k: v[1] for k, v in greek_letters.items()}
x(Τ) = A * cos(Ω * Τ + Θ)

Python also offers an alternative style of formatting that allows 
subscripts:

>>> print 'x({to[0]}) = A * cos({omega[1]} * {to[0]} + {theta[1]})'.format(
... **greek_letters)
x(τ) = A * cos(Ω * τ + Θ)





More information about the Python-list mailing list