简体   繁体   中英

How to print 'and' word. Dictionary inside a list

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?

This would work:

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

You can try this way

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

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"])

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, eg:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM