2

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...

GingerPlusPlus
  • 5,336
  • 1
  • 29
  • 52

3 Answers3

3

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")
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • that's some silly mistake indenting.... But yeah I understand what you pointed out and thanks for answering. :) –  Oct 30 '16 at 12:26
  • 1
    You should not be adding the strings together. That eats CPU and it's not pythonic! Instead use `%s` or `.format` which is more popular for python3 – Stam Kaly Oct 30 '16 at 13:52
  • while we're trying to be the most pythonic possible, you're right. Just copied the OP's code without changing it. Edited. – Jean-François Fabre Oct 30 '16 at 14:01
1

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')
Stam Kaly
  • 668
  • 1
  • 11
  • 26
0

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')
spyrostheodoridis
  • 508
  • 2
  • 8
  • 27