【发布时间】:2013-04-05 03:14:26
【问题描述】:
好的,所以我有以下行星字典,每个行星都有自己的字典,其中包含其规格:
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 中运行它时,行星名称及其规格打印在它下面,我只是不知道如何格式化它以在堆栈上以这种方式显示)
即:
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(),但这只是按字母顺序排列。有什么建议吗?
【问题讨论】:
-
你要什么顺序? “在字典中出现的顺序”是什么意思?字典不按任何顺序保存元素。
-
你不能那样做,字典不是用来排序的,它们主要是用来映射和检索的。您可以做的是构建一个元组列表 (x,y),其中 x 是键,y 是值。您可以使用循环按该顺序打印出键和值的元组列表,然后将该列表传递给
dict(),然后按该顺序打印后您将拥有字典。 -
对于您自己的实现:stackoverflow.com/questions/60848/…
-
啊,太糟糕了,我猜你知道的越多。谢谢你们让我知道
-
您或许可以使用
collections.OrderedDict。返回按属性之一排序的列表很容易。例如。sorted(d.items(), key=lambda (k,v):v['Distance from the sun'])
标签: sorting dictionary python-3.x formatting