user7091474
user7091474

Reputation:

Is there a better way to print these key-value pairs?

So this is some code I did working exercise 6-9 of Chapter 6 in Python Crash Course book.

favorite_places = {
'joe': {
    'paris': 'france',
    'hamburg': 'germany',
    'cairo': 'egypt',
    },
'anna': {
    'tripoli': 'libya',
    'tokyo': 'japan',
    'moskva': 'russia',
    },
'henry': {
    'sydney': 'australia',
    'quebec': 'canada',
    'rio de janeiro': 'brazil',
    }
}

for person, places in favorite_places.items():
    print(person.title() + "'s favorite places are: ")
    places = places.items()
    for place in places:
        print(place[0].title() + " in " + place[1].title() + ".")
    print("\n")

Then the output is like this:

Joe's favorite places are:
Cairo in Egypt.
Hamburg in Germany.
Paris in France.

Is there a way to just get the key-value from the places variable and print it the same way I did but without converting places to a list? I think it's a bit messy like this...

Upvotes: 2

Views: 65

Answers (3)

Stam Kaly
Stam Kaly

Reputation: 668

Format is now in fashion for me so here's another cool way of doing this:

for name, places in favorite_places.items():
    print("{}'s favorite places are:".format(name.capitalize()))
    for city, country in places.items():
        print("{} in {}.".format(city.capitalize(), country.capitalize()))
    print('\n')

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

by doing this

places = places.items()

in python 3 you're not converting to a list but you access an iterator which yields the key,value pair so it's the best way of doing it.

(python 2 equivalent is iteritems, in python 2 items returns a list of couples but the behaviour has changed in python 3)

(what surprises me most is 1) your indentation and 2) you'd be better off writing directly that without using an array or a temp variable (unpacking the couples directly in 2 variables is more elegant, and use format as stated in the comments which is more elegant & performant)

for town,country in places.items():
    print("{} in {}.".format(town.title(),country.title())
print("\n")

Upvotes: 3

spyrostheodoridis
spyrostheodoridis

Reputation: 518

A slightly shorter way (still using list though) would be:

for person in favorite_places:
    print("%s's favorite places are: " %person.title())
    [print('%s in %s.' %(i.title(),z.title())) for i,z in favorite_places[person].items()]
    print('\n')

Upvotes: 0

Related Questions