Home > Net >  Is there a more concise way to print this out by using the dictionary?
Is there a more concise way to print this out by using the dictionary?

Time:04-07

Is there a more concise way to print this out?

countries = {
    'france': ['paris', 'bordeaux', 'marseille'],
    }

for country, cities in countries.items():
    print(f"These are some of the cities of {country.title()}:", end = ' ')
    for city in cities:
        if city != cities[-1]:
            print(city.title(), end = ', ')
        else:
            print(f"{city.title()}.")

Expected output:

These are some of the cities of France: Paris, Bordeaux, Marseille.

CodePudding user response:

You can put any python expression into an f-string. The str.join method will add separator between list items. And python string literals within parenthesis such as in a function call can be written on multiple lines. So, your code can change to

countries = {
    'france': ['paris', 'bordeaux', 'marseille'],
    }

for country, cities in countries.items():
    print(f"These are some of the cities of {country.title()}: "
            f"{', '.join(city.title() for city in cities)}")

CodePudding user response:

You can replace the second loop (cities) with this single line:

print(", ".join(map(str.title, cities))   ".")

CodePudding user response:

What about this one-liner:

print(next(f'These are some of the cities of {k.title()}: {", ".join(map(str.title, v))}.' for k,v in countries.items()))

result

These are some of the cities of France: Paris, Bordeaux, Marseille.
  • Related