0

I want to print out the contents of a nested list structure.

Here is my nested list:

usa = ['New York', 'Chicago', 'Seattle']
canada = ['Vancouver', 'Toronto', 'Kelowna']
england = ['London', 'Liverpool', 'Birmingham']

countries = [usa, canada, england]

I want the output to look like:

usa: New york, Chicago, Seattle,
canada: Vancouver, Toronto, Kelowna,
england: London, Liverpool, Birmingham,

  • You'll have to do some pretty 'hacky' things to print the variable's name, could you hard code the name into the structure? – Collin Heist Oct 22 '20 at 16:51
  • Use a dictionary here, where the dictionary keys are the list names, and they map to the lists. Then you can just iterate using the dictionary's `items` method. – Carcigenicate Oct 22 '20 at 16:53

2 Answers2

0

heres a cool simle way to do that:

usa = ['New York', 'Chicago', 'Seattle']
canada = ['Vancouver', 'Toronto', 'Kelowna']
england = ['London', 'Liverpool', 'Birmingham']

print("usa: ", *usa)
print("canda: ", *canada)
print("england: ", *england)

#or if you want commas

print("usa: ", ", ".join(usa))
...
Ironkey
  • 2,568
  • 1
  • 8
  • 30
0

Try using a dictionary:

usa = ['New York', 'Chicago', 'Seattle']
canada = ['Vancouver', 'Toronto', 'Kelowna']
england = ['London', 'Liverpool', 'Birmingham']

dictionary = {'usa':usa,
              'canada':canada,
              'england':england}

for key in dictionary.keys():
    string = ', '.join(dictionary[key])
    print(f"{key}: {string}")

Output:

usa: New York, Chicago, Seattle
canada: Vancouver, Toronto, Kelowna
england: London, Liverpool, Birmingham
Sushil
  • 5,440
  • 1
  • 8
  • 26