1

I'm trying to create a simple 2D array of country names and capital cities. This was straightforward i Java, but I'm toiling in Python.

I'd like something along the lines of:

Scotland    Edinburgh
England    London
Wales     Cardiff

Any thoughts?

John Alexiou
  • 28,472
  • 11
  • 77
  • 133
Scotty55
  • 23
  • 3

4 Answers4

0

As an example, you could make two arrays, one for the capitals and one for the countries, and then by accessing their value at the same index you can get the capital city and its country!

capitalCities= ["Edinburgh", "London", "Cardiff"]

countries= ["Scotland", "England", "Wales"]

Enrico Cortinovis
  • 811
  • 3
  • 8
  • 31
0
>>> arr = [['england', 'london'], ['whales', 'cardiff']]
>>> arr
[['england', 'london'], ['whales', 'cardiff']]
>>> arr[1][0]
'whales'
>>> arr.append(['scottland', 'Edinburgh'])
>>> arr
[['england', 'london'], ['whales', 'cardiff'], ['scottland', 'Edinburgh']]

You would probably be better off using a dictionary though: How to use a Python dictionary?

luckydog32
  • 909
  • 6
  • 13
0

I agree with luckydog32, the dictionary should be a good solution to this.

capitolDict = {'england':'london', 'whales': 'cardiff'}
print(capitolDict.get('england'))
0

First of all, make a list of country name and their respective capital city.

countries = ['ScotLand','England','Wales']
capitals = ['Edinburgh','London','Cardiff']

Then, You can zip countries and capitals into a single list of tuple. Here, tuple is immutable sequence.

sequence = zip(countries,capitals)

Now, display:

for country, capital in sequence:
    print(country,capital)
  • Thanks - I'm teaching this to some school pupils and this goes way beyind what they need to know. But it's ideal for me and I'll look at using it when they get to a more advanced level. – Scotty55 Dec 03 '19 at 08:17