python-3.x - Why is the output of my dictionary in a random, shuffled order as opposed to the order that I want (Python 3.8.3)?
问题描述
I am trying to have my dictionary output information about a music album (the artist's name, the album's name, and the number of songs in the album) in that order. As you can see in my code, the number of songs in the album is not always passed to the function, and that is on purpose.
The problem is, my program is outputting the values of the dictionary in a random, shuffled order, as opposed to the order that I wrote above.
def make_album(artist, album_name, songs = None):
''' Makes a dictionary describing a music album'''
if songs:
album = {artist, album_name, songs}
else:
album = {artist, album_name}
return album
album1 = make_album("Guns n' Roses", "The Spaghetti Incident")
print(album1)
album2 = make_album("Pink Floyd", "The Wall", "10")
print(f"\n{album2}")
album3 = make_album("Smash Brothers", "All Stars")
print(f"\n{album3}")
This is an example of an output that I'm getting upon executing the program:
{'The Spaghetti Incident', "Guns n' Roses"}
{'10', 'The Wall', 'Pink Floyd'}
{'Smash Brothers', 'All Stars'}
Thank you!!!
Btw, this is my time ever asking a programming question on the internet! Brand new coder!!
Btw, I'm running Python 3.8.3.
解决方案
您正在使用set
s。集合在 Python 中本质上是无序的,打印它们可以产生任何顺序。
您想使用 ordered tuple
s 代替。所以而不是
album = {artist, album_name, songs}
你会写:
album = (artist, album_name, songs)
在这种情况下,更好的是使用 anamedtuple
或 class 代替。
推荐阅读
- c# - 输入将正确的选择值返回给控制器,但选择列表不是
- python-c-api - Python C++ API - 如何从 Python 访问/设置类属性?
- javascript - 等待加载 html 直到从异步进程加载引用的 js 值?
- wordpress - WordPress - 将开发构建推广到生产环境
- c# - MySql.Data.MySqlClient.MySqlException:''字段列表'中的未知列'Cantidad''
- r - 操纵滑块未出现在“情节”中
- python - 为什么我不能在这里使用 groupby 函数计算另一列的平均值?
- android - 登录测试不适用于 ArgumentCaptor
- c# - 在 Nunit 控制台上运行 Specflow 3.0 报告
- django - Django 教程。通用视图。context_object_name = 'latest_question_list'