A
A
Andrey Grinevich2015-10-15 19:34:43
Python
Andrey Grinevich, 2015-10-15 19:34:43

How to remove unnecessary parameters when formatting a string in Python?

Good day. There is a line like "Deal % (dam)s to enemy" and a huge kwarg'ov dictionary like
{some_value1: 112, some_value2:321, dam: 42 } formatting options from quargs?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
abcd0x00, 2015-10-16
@abcd0x00

>>> d = {'some_value1': 112, 'some_value2': 321, 'dam': 42, 'pam': 43}
>>> out = {k: d[k] for k in d if k in ('dam', 'pam')}
>>> out
{'dam': 42, 'pam': 43}
>>>

A
angru, 2015-10-16
@angru

% seems not to be advised to use, an alternative to str.format
as for the question: it’s better to reconsider the architecture so that you know the data needed for the string, but if you want to pervert, you can parse the string with a regular expression, pull out the necessary keys and remove them from the dictionary

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question