문제

I am trying to combine a dictionary comprehension and an inline if statement. The comprehension loops over all items and as long as the item has not the key id it creates a new key: job[old_key].

Code

job = {'id':1234, 'age':17, 'name':'dev'}
args = {'job[%s]' % k:v if k != 'id' else k:v for k, v in job}

Wished output

print args
{'id':1234, 'job[age]':17, 'job[name]':'dev'}

A SyntaxError was raised.

args = {'job[%s]' % k:v if k != 'key' else k:v for k, v in job}
                                            ^
SyntaxError: invalid syntax

However, when I try to run my script Python complains about k:v. How can I combine a dictionary comprehension and an inline if statement?

Note: I know that I can easily achieve that task with a for loop, but I just want to combine these two elements.

도움이 되었습니까?

해결책

The key and value parts are separate expressions. Use the conditional expression in just the key part:

args = {'job[%s]' % k if k != 'id' else k: v for k, v in job.iteritems()}

The : is not part of either expression, only of the dictionary comprehension syntax. You also need to loop over both keys and values; in Python 2, use job.iteritems(), Python 3, job.items().

Demo:

>>> job = {'id':1234, 'age':17, 'name':'dev'}
>>> {'job[%s]' % k if k != 'id' else k: v for k, v in job.iteritems()}
{'id': 1234, 'job[age]': 17, 'job[name]': 'dev'}

다른 팁

Extending the other answer, you can make it more readable as follows

get_key = lambda k: ('job[%s]' if k != 'id' else '%s') % k
args = { get_key(key): val for key, val in job.iteritems()}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top