Recently, I found ''.format
function very useful because it can improve readability a lot comparing to the %
formatting.
Trying to achieve simple string formatting:
data = {'year':2012, 'month':'april', 'location': 'q2dm1'}
year = 2012
month = 'april'
location = 'q2dm1'
a = "year: {year}, month: {month}, location: {location}"
print a.format(data)
print a.format(year=year, month=month, location=location)
print a.format(year, month, location)
Whilst two first prints do format as I expect (yes, something=something
looks ugly, but that's an example only), the last one would raise KeyError: 'year'
.
Is there any trick in python to create dictionary so it will automatically fill keys and values, for example somefunc(year, month, location)
will output {'year':year, 'month': month, 'location': location}
?
I'm pretty new to python and couldn't find any info on this topic, however a trick like this would improve and shrink my current code drastically.
Thanks in advance and pardon my English.