Python function ".format"

Recently, I found the feature ''.formatvery useful, as it can significantly improve readability compared to 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)

While the first two prints make the format, as I expect (yes, something=somethingit looks ugly, but just for example), the latter will pick up KeyError: 'year'. Is there a trick in python to create a dictionary so that it automatically populates keys and values, e.g. somefunc(year, month, location)outputs {'year':year, 'month': month, 'location': location}?

I am new to python and cannot find any information on this topic, however such a trick would improve and shorten my current code.

Thanks in advance and apologize for my English.

+5
5

print

print a.format(**data)

, , , .

def trans(year, month, location):
    return dict(year=year, month=month, location=location)
+6
data = {'year':2012, 'month':'april', 'location': 'q2dm1'}
a = "year: {year}, month: {month}, location: {location}"

print a.format(**data)

.. , . .format(year=data['year'], ...) , .

- , "kwargs". SO

+3

dict() :

dict(year=yeah, month=month, location=location)

dict, , kwargs.

, .format():

>>> a = 'year {0} month {1} location {2}'
>>> print a.format(2012, 'april', 'abcd')
year 2012 month april location abcd

, - , compact() PHP ( dict ), , . .

+1

locals():

a.format(**locals())

, : , .

:

a.format(**{k:v for k,v in locals() if k in ('year', 'month')})
# or; note that if you move the lambda expression elsewhere, you will get a different result
a.format(**(lambda ld = locals(): {k:ld[k] for k in ('year', 'month')})())

, (, , dict).

+1

Python 3.6, (f-), :

year = 2012
month = 'april'
location = 'q2dm1'
a = f"year: {year}, month: {month}, location: {location}"
print(a)

:

data = {'year': 2012, 'month': 'april', 'location': 'q2dm1'}
a = f"year: {data['year']}, month: {data['month']}, location: {data['location']}"
print(a)

f .

PEP 498: :

'f' , str.format(). , . , , format():

>>>
>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}"  # nested fields
'result:      12.35'

...

0

All Articles