好的,所以我有以下行星字典,每个行星都有自己的字典,其中包含其规格:
d={
'Mercury':{
'Distance from the sun' : 58,
'Radius' : 2439.7,
'Gas planet?' : False,
'Atmosphere?' : True,
'Moons' : []},
'Jupiter':{
'Distance from the sun' : 483,
'Radius' : 69911,
'Gas planet?' : True,
'Atmosphere?' : True,
'Moons' : ['Io', 'Ganymede', 'Callisto', 'Europa', 'Adrastea']},
'Uranus':{
'Distance from the sun' : 3000,
'Radius' : 25559,
'Gas planet?' : True,
'Atmosphere?' : True,
'Moons' : ['Miranda', 'Ariel', 'Umbriel', 'Titania', 'Oberon']},
'Mars':{
'Distance from the sun' : 207,
'Radius' : 3396.2,
'Gas planet?' : False,
'Atmosphere?' : True,
'Moons' : ['Phobos', 'Deimos']},
'Earth':{
'Distance from the sun' : 150,
'Radius' : 6371.0,
'Gas planet?' : False,
'Atmosphere?' : True,
'Moons' : ['Moon']},
'Venus':{
'Distance from the sun' : 108,
'Radius' : 6051.8,
'Gas planet?' : False,
'Atmosphere?' : True,
'Moons' : []},
'Saturn':{
'Distance from the sun' : 1400,
'Radius' : 60268,
'Gas planet?' : True,
'Atmosphere?' : True,
'Moons' : ['Pan', 'Prometheus', 'Titan', 'Phoebe', 'Rhea']},
'Neptune':{
'Distance from the sun' : 4500,
'Radius' : 24764,
'Gas planet?' : True,
'Atmosphere?' : True,
'Moons' : ['Triton', 'Nereid', 'Proteus', 'Naiad', 'Thalassa']}}`
基本上我想要做的是按照它在字典中出现的顺序打印它,所以我使用了代码:
for planets in sorted(d.keys()):
print(planets)
for k,v in sorted(d[planets].items()):
print(k, ":", v)
然而,这会产生每个行星的随机顺序和每个行星描述的关键值。(当我在 python 中运行它时,行星名称及其规格打印在它下面,我只是不知道如何格式化它以在堆栈上以这种方式显示它)
IE:
Neptune
Moons : ['Triton', 'Nereid', 'Proteus', 'Naiad', 'Thalassa']
Radius : 24764
Distance from the sun : 4500
Gas planet? : True
Atmosphere? : True
Jupiter
Moons : ['Io', 'Ganymede', 'Callisto', 'Europa', 'Adrastea']
Radius : 69911
Distance from the sun : 483
Gas planet? : True
Atmosphere? : True
Earth
Moons : ['Moon']
Radius : 6371.0
Distance from the sun : 150
Gas planet? : False
Atmosphere? : True
Mercury
Moons : []
Radius : 2439.7
Distance from the sun : 58
Gas planet? : False
Atmosphere? : True
Mars
Moons : ['Phobos', 'Deimos']
Radius : 3396.2
Distance from the sun : 207
Gas planet? : False
Atmosphere? : True
Uranus
Moons : ['Miranda', 'Ariel', 'Umbriel', 'Titania', 'Oberon']
Radius : 25559
Distance from the sun : 3000
Gas planet? : True
Atmosphere? : True
Venus
Moons : []
Radius : 6051.8
Distance from the sun : 108
Gas planet? : False
Atmosphere? : True
Saturn
Moons : ['Pan', 'Prometheus', 'Titan', 'Phoebe', 'Rhea']
Radius : 60268
Distance from the sun : 1400
Gas planet? : True
Atmosphere? : True
我试过使用sorted()
,但这只是按字母顺序排列。有什么建议么?