Home > OS >  How to print 'and' word. Dictionary inside a list
How to print 'and' word. Dictionary inside a list

Time:01-26

so i have a dictionary inside a list. And list inside that dictionary.

travel_log =[
{
    "country": "Russia",
    "visits": 2,
    "cities": ["Moscow", "Saint Petersburg"]
},
]

i want to print out:

You've been to Moscow and Saint Petersburg.

how?

CodePudding user response:

This would work :

print(f"You have been to {travel_log[0]['cities'][0]} and {travel_log[0]['cities'][0]}")

CodePudding user response:

You can try this way

print("You've been to"   " and ".join(travel_log[0]['cities']))

CodePudding user response:

Try this please:

for country in travel_log:
cities = ""
cities_size = len(country["cities"]) - 1
for idx, city in enumerate(country["cities"]):
    if idx > 0:
        if cities_size == idx:
            cities  = " AND "
        else:
            cities  = ", "

    cities  = city
    
print("You've been to " cities " at " country["country"])

CodePudding user response:

There is convenient inflect package. You need to install it with pip install inflect

import inflect

travel_log =[
{
    "country": "Russia",
    "visits": 2,
    "cities": ["Moscow", "Saint Petersburg"]
},
]

p = inflect.engine()
for journey in travel_log:
    print(f"You have been to {p.join(journey['cities'])}") 

output

You have been to Moscow and Saint Petersburg

if more than 2 elements it will be, e.g.:

You have been to Moscow, Volgograd, and Saint Petersburg

The package offers more convenient functionality as well - correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words.

  •  Tags:  
  • Related