gpt4 book ai didi

python - 仅打印 dict 值

转载 作者:行者123 更新时间:2023-12-01 03:05:41 27 4
gpt4 key购买 nike

我试图弄清楚为什么我的循环打印字典中的所有内容而不仅仅是值

films = {
"2005": ["Munich", "Steven Spielberg"],
"2006": [["The Prestige", "Christopher Nolan"], ["The Departed", "Martin Scorsese"]]
}

for year in movies:
print (year)
for x in films[year]:
print (films[year])

我希望它像这样打印

2005
Munich, Steven Spielberg

2006
The prestige, Christopher Nolan
the Departed, Martin Scorsese

但是它的打印方式是这样的,带有括号和撇号

2005
['Munich', 'Steven Spielberg']

最佳答案

您没有使用x(我建议一个更好的名称)。

此代码适用于 Python 2.7 和 Python 3.x:

films = {
"2005": ["Munich", "Steven Spielberg"],
"2006": [["The Prestige", "Christopher Nolan"], ["The Departed", "Martin Scorsese"]]
}

for year in sorted(films.keys()):
print(year)
if isinstance(films[year][0], list):
films_list = films[year]
else:
films_list = [films[year]]
for film in films_list:
print(", ".join(film))
print("")

关于python - 仅打印 dict 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43458061/

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