本文介绍了如何使用Python循环{}中的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
a = {0:'000000',1:'11111',3:' 333333',4:'444444'}
b = {i:j +'www'for i,j in a.items()}
打印b
并显示错误:
文件 g.py,第7行
b = {i:j +'www'对于a.items()中的i,j}
^
SyntaxError:语法无效
我该如何纠正?
解决方案
{i:j +'www'for i,j in a.items()}
在Python 3中效果很好。 p>
您可以在此处看到:(请注意,我将print作为Python 3中的函数调用)。
如果您< Python 3,那么它将给您这个错误。
要执行这种类型的概念,必须执行列表/生成器表达式,以创建键,值的元组。一旦发生这种情况,您可以调用dict()接受一个元组列表。
dict((i,j +'www' )对于a.items())中的i,j
This is my code :
a = {0:'000000',1:'11111',3:'333333',4:'444444'}
b = {i:j+'www' for i,j in a.items()}
print b
and it shows error :
File "g.py", line 7
b = {i:j+'www' for i,j in a.items()}
^
SyntaxError: invalid syntax
How can I correct this?
解决方案
{i:j+'www' for i,j in a.items()}
Dictionary Comprehension works fine in Python 3.
As you can see here: http://ideone.com/tbXLA (note, I am calling print as a function in Python 3).
If you have < Python 3, then it will give you this error.
To do this type of concept, you must do list/generator expression which creates a tuple of key, value. Once this happens, you can call dict() which accepts a list of tuples.
dict((i,j+'www') for i,j in a.items())
这篇关于如何使用Python循环{}中的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!