转换词典

2024-10-03 00:27:10 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的字典

dict = {'apple':'der Apfel', 'ant':'die Ameise', 'asparagus':'der Spargel'}

我想得到一个输出:

^{pr2}$

我对字典不熟悉 请帮忙

我试过了

^{3}$

但它不起作用


Tags: apple字典dictantderdiepr2asparagus
3条回答

这能做你想做的吗?在

(编辑:更新为新的输出格式)

my_dict = {'apple':'der Apfel', 'ant':'die Ameise', 'asparagus':'der Spargel'}

print 'dictionary for a'
for k, v in my_dict.iteritems():
     print '%s:%s' % (k, v)

产量:

^{pr2}$

请注意,此订单与您发布的订单不同,但问题并未说明订单是否重要。在

正如@wim正确建议的那样,最好不要使用dict作为变量名。在

如果您只是尝试遍历字典,以打印键和值对:

>>> dict_ = {'apple':'der Apfel', 'ant':'die Ameise', 'asparagus':'der Spargel'}
>>> for k,v in dict_.iteritems():
...   print k, ':', v
... 
ant : die Ameise
asparagus : der Spargel
apple : der Apfel

在一行中使用生成器表达式:

^{pr2}$

另外,请避免使用dict作为变量名,因为它隐藏了内置的内容。在

如果您只想将每个键和值对打印成一行,可以执行以下操作:

dict = {'apple':'der Apfel', 'ant':'die Ameise', 'asparagus':'der Spargel'}
for key, value in dict.items():
  print key + ':', value,
print

输出的顺序可能与创建字典时的顺序不同。迭代字典并不能保证任何特定的顺序,除非您专门对键进行排序,例如使用sorted()内置函数:

^{pr2}$

相关问题 更多 >