列表理解,但字典?

时间:2016-09-16 18:20:57

标签: python python-3.x list-comprehension dictionary-comprehension

更加pythonic的做法如下?在这个例子中,我试图将注释(一个字典)构建为键值对,其中键是未修改版本,值是来自函数的返回值,其中键作为arg传递。 / p>

def func(word):
    return word[-1:-6:-1].upper()

subs = {
    'ALLOWED': ['one', 'two'],
    'DISALLOWED': ['three', 'four']
}

comments = {}
for sub in subs['ALLOWED']:
    # reverse and uppercase
    comments[sub] = func(sub)

print(comments)

有人有推荐吗?完成这一点并不是很重要,但我喜欢学习python习语以及让我的代码更加pythonic的方法。谢谢!

2 个答案:

答案 0 :(得分:4)

使用dict comprehension代替在comments = {key: func(key) for key in subs['ALLOWED']} 循环中构建词典:

{{1}}

答案 1 :(得分:0)

删除循环并使用字典理解将其替换为函数内部。然后,您可以简单地返回它。

此外,您可以使用word反转字符串[::-1],而不是您正在使用的复杂[-1:-6:-1]切片:

def func(words):
    return {word: word[::-1].upper() for word in words} 

这会产生同样的结果:

comments = func(subs['ALLOWED'])
print(comments)
# {'two': 'OWT', 'one': 'ENO'}
相关问题