gpt4 book ai didi

python - 转换字典

转载 作者:行者123 更新时间:2023-11-28 20:51:14 25 4
gpt4 key购买 nike

这是我的字典

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

我想得到一个输出:

dictionary for a
apple: der Apfel
ant:die Ameise
asparagus:der Spargel

我是字典新手请帮忙

我试过

def tutorial8_part2():
dict = {'apple':'der Apfel', 'ant':'die Ameise', 'asparagus':'der Spargel'}
dictList = dict.items()
for key, value in dict.iteritems():
temp = []
aKey = key
aValue = value
temp.append(aKey)
temp.append(aValue)
dictList.append(temp)
print dictList.append(temp)

但它不起作用

最佳答案

如果你只是想在一长行中打印出每个键值对,你可以这样做:

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

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

for key, value in sorted(dict_.items()):  
print "{0}: {1}".format(key, value)

关于python - 转换字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10509527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com