首页 > 解决方案 > 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.

标签: python-3.xdictionary

解决方案


您正在使用sets。集合在 Python 中本质上是无序的,打印它们可以产生任何顺序。

您想使用 ordered tuples 代替。所以而不是

album = {artist, album_name, songs}

你会写:

album = (artist, album_name, songs)

在这种情况下,更好的是使用 anamedtuple或 class 代替。


推荐阅读