Sorting output of a dictionary -
alright have following dictionary of planets, , each planet has own dictionary containing specs: d={ 'mercury':{ 'distance sun' : 58, 'radius' : 2439.7, 'gas planet?' : false, 'atmosphere?' : true, 'moons' : []}, 'jupiter':{ 'distance sun' : 483, 'radius' : 69911, 'gas planet?' : true, 'atmosphere?' : true, 'moons' : ['io', 'ganymede', 'callisto', 'europa', 'adrastea']}, 'uranus':{ 'distance sun' : 3000, 'radius' : 25559, 'gas planet?' : true, 'atmosphere?' : true, 'moons' : ['miranda', 'ariel', 'umbriel', 'titania', 'oberon']}, 'mars':{ 'distance sun' : 207, 'radius' : 3396.2, 'gas planet?' : false, 'atmosphere?' : true, 'moons' : ['phobos', 'deimos']}, 'earth':{ 'distance sun' : 150, 'radius' : 6371.0, 'gas planet?' : false, 'atmosphere?' : true, 'moons' : ['moon']}, 'venus':{ 'distance sun' : 108, 'radius' : 6051.8, 'gas planet?' : false, 'atmosphere?' : true, 'moons' : []}, 'saturn':{ 'distance sun' : 1400, 'radius' : 60268, 'gas planet?' : true, 'atmosphere?' : true, 'moons' : ['pan', 'prometheus', 'titan', 'phoebe', 'rhea']}, 'neptune':{ 'distance sun' : 4500, 'radius' : 24764, 'gas planet?' : true, 'atmosphere?' : true, 'moons' : ['triton', 'nereid', 'proteus', 'naiad', 'thalassa']}}
essentially want print in order appears in dictionary, used code:
for planets in sorted(d.keys()): print(planets) k,v in sorted(d[planets].items()): print(k, ":", v)
however yields random order of each planet , key value each planet's description. (the planet name , specs printed underneath when run in python, didn't know how format show way on stack)
i.e.: neptune moons : ['triton', 'nereid', 'proteus', 'naiad', 'thalassa'] radius : 24764 distance sun : 4500 gas planet? : true atmosphere? : true jupiter moons : ['io', 'ganymede', 'callisto', 'europa', 'adrastea'] radius : 69911 distance sun : 483 gas planet? : true atmosphere? : true earth moons : ['moon'] radius : 6371.0 distance sun : 150 gas planet? : false atmosphere? : true mercury moons : [] radius : 2439.7 distance sun : 58 gas planet? : false atmosphere? : true mars moons : ['phobos', 'deimos'] radius : 3396.2 distance sun : 207 gas planet? : false atmosphere? : true uranus moons : ['miranda', 'ariel', 'umbriel', 'titania', 'oberon'] radius : 25559 distance sun : 3000 gas planet? : true atmosphere? : true venus moons : [] radius : 6051.8 distance sun : 108 gas planet? : false atmosphere? : true saturn moons : ['pan', 'prometheus', 'titan', 'phoebe', 'rhea'] radius : 60268 distance sun : 1400 gas planet? : true atmosphere? : true
i've tried using sorted()
puts in alphabetical order. suggestions?
this cannot done. python dictionaries
not make promises printed order.
Comments
Post a Comment