11 Replies - 1368 Views - Last Post: 19 November 2012 - 05:57 PM Rate Topic: -----

#1 medaa  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 106
  • Joined: 24-October 12

Print output question

Posted 19 November 2012 - 02:14 PM

I have this dictionary, involving a nested loop,

'Mercury':{
               'Radius':'2,439.7 km',
               'Distance from the sun-':'58 million km',
               'Moons':[],
               'Atmosphere?':'True',
               'Gas planet?':'False',


I want the output to look like:

Mercury
Distance from the sun : 58
Radius : 2439.7
Gas planet? : False
Atmosphere? : True
Moons : []


Ive tried using '/n' but it didnt work, but I keep getting
{'\nGas planet?': 'False', '\nDistance from the sun': '58 million km', 'Radius': '2,439.7 km', '\nMoons': [], '\nAtmosphere?': 'True'}


Is there any other way?? Help please.

Is This A Good Question/Topic? 0
  • +

Replies To: Print output question

#2 Python_4_President  Icon User is offline

  • D.I.C Regular

Reputation: 53
  • View blog
  • Posts: 321
  • Joined: 13-August 11

Re: Print output question

Posted 19 November 2012 - 02:30 PM

Try this. Change "planets" to whatever your dictionary is called.

for key in planets.keys():
    print key
    print "\n".join(["{0} : {1}".format(k, v) for k, v in planets[key].iteritems()])




The join method will join items in a list (or other iterables, like a set, or tuple) with the contents of the string the method was called from (in this case, "\n")

That means all the items of the list will be joined by newline characters.

Inside the join statement is a list comprehension. A list comprehension is a convenient way to perform a certain operation on all the items of a list. A list comprehension returns a list -> This is what join operates on.

It's the same as saying,

for k, v in planets[key].iteritems():
    print "{0} : {1}".format(k, v)



Dictionaries have these convenience methods which are helpful to you now.
keys(), values(), and iteritems()

keys() will give you a list with the keys in the dictionary as its elements.
values() will give you a list with the values in the dictionary as its elements.
iteritems() will give you an iterable which allows you to iterate over tuples containing both the key, and the value.


>>> d['Mercury'].iteritems()
<dictionary-itemiterator object at 0x9baa6bc>



As a typical for loop
>>> for key_value_tuple in d['Mercury'].iteritems():
...     print key_value_tuple
... 
('Atmosphere?', 'True')
('Moons', [])
('Radius', '2,439.7 km')
('Gas planet?', 'False')
('Distance from the sun-', '58 million km')



as a list comprehension:
>>> [key_value_tuple for key_value_tuple in d['Mercury'].iteritems()]
[('Atmosphere?', 'True'), ('Moons', []), ('Radius', '2,439.7 km'), ('Gas planet?', 'False'), ('Distance from the sun-', '58 million km')]




We're interested in splitting up and printing the key value pairs, though.
Since each dictionary entry contains a key and a value, we can say things like:
for key, value in d.iteritems():
    print key, value



the format method of strings lets you be classy with the way you present the data. Since you're doing easy stuff, we used only the most basic features of the format method.

The format method will fill in entries like {0}, {1}, {2} in the string it is called from with the parameters passed to it.

print "{0} {1}{2}".format("Hello", "World", "!")




You also could have done:
for key in planets.keys():
    print key
    print "\n".join([str(k) + " : " + str(v) for k, v in planets[key].iteritems()])




As well as:
for key in planets.keys():
    print key
    for k, v in planets[key].iteritems():
        print str(k) + " : " + str(v) #I use str here because you may not always have strings as values and it doesn't hurt anything to use str() on a string


This post has been edited by Python_4_President: 19 November 2012 - 02:57 PM

Was This Post Helpful? 2
  • +
  • -

#3 medaa  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 106
  • Joined: 24-October 12

Re: Print output question

Posted 19 November 2012 - 03:18 PM

Best explanation so far, thank you.
Can I ask one more thing, for example if I wanted to find the furthest planet from the sun, can i write
for x in planets(distance from the sun):
           if x is>distance from the sun 
           print(x)

Was This Post Helpful? 0
  • +
  • -

#4 Python_4_President  Icon User is offline

  • D.I.C Regular

Reputation: 53
  • View blog
  • Posts: 321
  • Joined: 13-August 11

Re: Print output question

Posted 19 November 2012 - 03:48 PM

With the structure of your current dictionary, doing so would be quite convoluted (would involve splitting the value, converting the numeric part of the string to, eg, int or float, and then raising the value, in the case of distance from the sun, to the proper power.)


It would be much easier if your dictionary looked like this:
d = {}
d['Mercury'] = {
               'Radius':(2439.7,'km'),  #d[key]['radius'][0] is the value of the radius, and d[key]['radius'][1] is the unit representative of the value
               'Distance from the sun-':(58*10**6, 'km'),
               'Moons':[],
               'Atmosphere?':'True',
               'Gas planet?':'False' }



If kilometers is all you will be using, then you don't need the tuple there. You can just have the value, and when you print out the information, just append km to the resultant string.


This is kind of a bad example, but that's mostly because at this point, given the complexity of your dictionary, you probably ought to start thinking about it in terms of classes instead of dictionaries.

d = {}
d['Mercury'] = {
               'Radius':(2439.7,'km'),  #d[key]['radius'][0] is the value of the radius, and d[key]['radius'][1] is the unit representative of the value
               'DistanceFromSun':(58*10**6, 'km'),
               'Moons':[],
               'Atmosphere?':'True',
               'Gas planet?':'False' }
d['Mars'] = {
               'Radius':(2420.7,'km'),  #d[key]['radius'][0] is the value of the radius, and d[key]['radius'][1] is the unit representative of the value
               'DistanceFromSun':(54*10**6, 'km'),
               'Moons':[],
               'Atmosphere?':'True',
               'Gas planet?':'False' }
d['Venus'] = {
               'Radius':(2300.7,'km'),  #d[key]['radius'][0] is the value of the radius, and d[key]['radius'][1] is the unit representative of the value
               'DistanceFromSun':(56*10**6, 'km'),
               'Moons':[],
               'Atmosphere?':'True',
               'Gas planet?':'False' }

import operator
def find_furthest_from_sun(d):
	keys_and_distances = {}
	for key in d.keys():
	    keys_and_distances[key] = d[key]['DistanceFromSun'][0]
	return sorted(keys_and_distances, key=operator.itemgetter(1), reverse=True)[0] #sorted returns a sorted list. Smallest to biggest, by default. reverse=True reverses that. [0] will then be the biggest in the list.



result = find_furthest_from_sun(d)
print "{0} is the furthest planet from the sun. It is {1}{2} away.".format(result, d[result]['DistanceFromSun'][0], d[result]['DistanceFromSun'][1])




operator is kind of complicated to describe, and the documentation doesn't do that great a job, either.

Basically, sorted takes an iterable object (dict, list, etc) and sorts it by some pretty nifty rules that Jon.Kiparsky explained pretty well here.

You can optionally specify a key to sort by. Since you're sorting a dictionary and looking for the maximum distance (which is in the value part of the key, value pair), you'll want to sort by value instead of by key.

operator.itemgetter lets you do that.

If you did operator.itemgetter(0), you'd be sorting by key, in which case, Venus would be the greatest (ord('V') > ord('M'))

58 million is bigger than 56 and 54 million, so it returns the list with Mercury first, because my fudged numbers wound up with it being the furthest away.

This post has been edited by Python_4_President: 19 November 2012 - 04:12 PM

Was This Post Helpful? 0
  • +
  • -

#5 medaa  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 106
  • Joined: 24-October 12

Re: Print output question

Posted 19 November 2012 - 04:00 PM

This is how my dictionary looks like right now

Planets={
    'Mercury':{
               'Radius':'2439.7',
               'Distance from the sun':'58',
               'Moons':[],
               'Atmosphere?':'True',
               'Gas planet?':'False',
    },
    'Venus':{
        'Radius':'6051.8',
        'Distance from the sun':'108',
        'Moons':[],
        'Atmosphere?':'True',
        'Gas planet?':'False'
    },
    'Earth':{
        'Radius':'6371.0,'
        #'Distance from the sun':'150',
        #'Moons':['Moon'],
        #'Atmosphere?':'True',
        #'Gas planet?':'False'
    },
    'Mars':{
        'Radius':'3396.2',
        'Distance from the sun':'207',
        'Moons':['Phobos','Deimos'],
        'Atmosphere?':'True',
        'Gas planet?':'False'
    },
    'Jupiter':{
        'Radius':'69911',
        'Distance from the sun':'483',
        'Moons':['Io', 'Ganymede', 'Callisto', 'Europa', 'Adrastea'],
        'Atmosphere?':'True',
        'Gas planet?':'True'
    },
    'Saturn':{
        'Radius':'60268',
        'Distance from the sun':'1400',
        'Moons':['Pan', 'Prometheus', 'Titan', 'Phoebe', 'Rhea'],
        'Atmosphere?':'True',
        'Gas planet?':'True'
    },
    'Uranus':{
        'Radius':'25559',
        'Distance from the sun':'3000',
        'Moons':['Miranda', 'Ariel', 'Umbriel', 'Titania', 'Oberon'],
        'Atmosphere?':'True',
        'Gas planet?':'True' 
    },
    'Neptune':{
        'Radius':'24764',
        'Distance from the sun':'4500',
        'Moons':['Triton', 'Nereid', 'Proteus', 'Naiad', 'Thalassa'],
        'Atmosphere?':'True',
        'Gas planet?':'True'
    },
}


I know how to access one value at a time
for example
print(Planets['Neptune']['Distance from the sun'])
can i use a loop that will do through and find the greatest distance and print out the planet?
Was This Post Helpful? 0
  • +
  • -

#6 Python_4_President  Icon User is offline

  • D.I.C Regular

Reputation: 53
  • View blog
  • Posts: 321
  • Joined: 13-August 11

Re: Print output question

Posted 19 November 2012 - 04:24 PM

Yeah, review the function I made. You'd just need to modify it a little bit to make it fit your new dictionary (remember to convert the string distances to ints or floats to avoid unexpected sorting results)


sorted returns a sorted list. Smallest to biggest, by default. reverse=True reverses that. [0] will then be the key of the biggest(furthest away planet) in the list.

import operator
def find_furthest_from_sun(d):
	keys_and_distances = {}
	for key in d.keys():
	    keys_and_distances[key] = d[key]['DistanceFromSun'][0] #this line needs to change a bit, can you see how?
	list_of_planet_names_from_furthest_away_from_sun_to_nearest = sorted(keys_and_distances.iteritems(), key=operator.itemgetter(1), reverse=True)
    return list_of_planet_names_from_furthest_away_from_sun_to_nearest[0]


This post has been edited by Python_4_President: 19 November 2012 - 04:51 PM

Was This Post Helpful? 0
  • +
  • -

#7 medaa  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 106
  • Joined: 24-October 12

Re: Print output question

Posted 19 November 2012 - 04:41 PM

Is that the only way??, I don't quiet understand.
Was This Post Helpful? 0
  • +
  • -

#8 Python_4_President  Icon User is offline

  • D.I.C Regular

Reputation: 53
  • View blog
  • Posts: 321
  • Joined: 13-August 11

Re: Print output question

Posted 19 November 2012 - 04:54 PM

At what point do you get lost?

It's not a tricky operation, it's just ugly to write. Employers love testing people on how to sort things by key and by value for that reason. I'm happy to explain it to you another way, but I'm not sure where to focus my attention.

Do you understand importing modules?
Do you understand function definitions?
Do you understand passing parameters to functions?
You should understand the for loop at this point, and getting data from dictionaries.

I THINK the hard part now is sorting the dictionary by value. Am I right?
Was This Post Helpful? 0
  • +
  • -

#9 medaa  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 106
  • Joined: 24-October 12

Re: Print output question

Posted 19 November 2012 - 05:06 PM

Ive been doing programming for 3 months now, so I still dont know what importing modules and function definitions are.
Sorry, im slowly learning
Was This Post Helpful? 0
  • +
  • -

#10 Python_4_President  Icon User is offline

  • D.I.C Regular

Reputation: 53
  • View blog
  • Posts: 321
  • Joined: 13-August 11

Re: Print output question

Posted 19 November 2012 - 05:20 PM

Oh, wow.
Functions are the best!

def do_some_stuff(): #This is a basic function
    print "Doing some stuff."

def do_some_other_stuff(more_stuff): #This is a basic function that takes an argument
    print "Doing ", more stuff

def sort_my_list(my_list): #This is a basic function that takes an argument and returns something
    return sorted(my_list)

def sort_my_list_with_option_to_reverse_it(my_list, reverseIt=False): #This is a less basic function that takes an argument, an optional keyword argument, and returns something
    return sorted(my_list, reverse=reverseIt)


do_some_stuff()
do_some_other_stuff("Lots of code writing.")
print sort_my_list(["Alpha", "Bravo", "Charlie", "Daniels", "Echo", "Frankenstein", "Chupacabra"])
print sort_my_list_with_option_to_reverse_it(["k", "r", "i", "n", "o"], reverseIt=True)






Try giving an argument to do_some_stuff()
try not giving an argument to do_some_other_stuff()
try not giving the reverseIt argument to sort_my_list_with_option_to_reverse_it()



Modules contain functions and classes and such that do lots of work for you. When you import them, you get access to their contents.


An example module is:

simple_module.py
def importable_function():
    print "You got me!"



test.py

import simple_module #most overhead, least confusion.
simple_module.importable_function()

from simple_module import importable_function #A happy middle
importable_function()

from simple_module import * #I usually regret doing this
importable_function() 




operator is a module.
itemgetter is a class in that module that does some nifty magic when you need to sort a dictionary by value. It enables you to specify a key to sort by.



import operator

d = {'a':0, 'b':1, 'c':2, 'd':3, 'e':4, 'f':5}


print "Unsorted: ", d
print "Sorted keys in ascending order: ", sorted(d.keys())
print "Sorted keys in descending order: ", sorted(d.keys(), reverse=True)
print "Sorted values in ascending order: ", sorted(d.values())
print "Sorted values in descending order: ", sorted(d.values(), reverse=True)
print "Sorted by value in ascending order: ", sorted(d.iteritems(), key=operator.itemgetter(1))
print "Sorted by value in descending order: ", sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True)
print "The biggest number in d is: ", sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True)[0][1]
print "The smallest number in d is: ", sorted(d.iteritems(), key=operator.itemgetter(1), reverse=False)[0][1]
print "The letter of the smallest number in d is: ", sorted(d.iteritems(), key=operator.itemgetter(1), reverse=False)[0][0]
print "The letter of the biggest number in d is: ", sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True)[0][0]


This post has been edited by Python_4_President: 19 November 2012 - 05:33 PM

Was This Post Helpful? 1
  • +
  • -

#11 medaa  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 106
  • Joined: 24-October 12

Re: Print output question

Posted 19 November 2012 - 05:55 PM

Heres an example I found online : Write a Python program that has 3 functions : main, build_dictionary and pretty_print. The main function asks the user to enter the name of file (names.txt), opens file for reading and calls the build_dictionary function. The build_dictionary function accepts the file handler in its parameter, processes the file to build and return a dictionary with last names as keys and the count of last names as values. The build_dictionary function ignores blank lines and any lines that do not contain a person’s name. The main function then calls another function called pretty_print that accepts the dictionary (that was returned by build_dictionary) as a parameter and prints the contents of the dictionary.

If I wanted to find the output, I would take what Im using with dictionaries and put it with what you just taught me and run the program

so this is how much I can do,

def build_dictionary(name1):
    dict={}
    for line in infile:
    if line!='' or line[0]!='#':
        lst=line.split(" ")
        count=count+1
        
        while "" in lst:
            lst.remove("")



def main():
    import os.path
    while True:
        try:
            name1=input("Enter input name:")
            infile=open(name1,"r")
            name2=input("Enter output name:")
            while(os.path.isfile(name2)):
                name2=input("File exists. Enter new output name:")
            ofile=open(name2, "w")
            break
        except:
            print("Error in code")
        
main()


I dont get how to pass parameters around.
Was This Post Helpful? 0
  • +
  • -

#12 Python_4_President  Icon User is offline

  • D.I.C Regular

Reputation: 53
  • View blog
  • Posts: 321
  • Joined: 13-August 11

Re: Print output question

Posted 19 November 2012 - 05:57 PM

Now you're getting it.

As an aside, there's a module that comes with the standard Python distribution called pprint which contains a function called pprint which probably does the same thing as the "pretty_print" in the example.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1