0

I have 2 .py files (data.py, access.py)

In access.py, I have a few strings:

Japan = ['brown', 'cow', 'around']
Korea = ['black', 'chicken', '344']
China = ['grey', '3411', 'leaf']
Indonesia = ['red', 'green', '']

In data.py, I have a module:

def whichcolour(country)
       print("access + country[1]")  # Doesn't work

My Results

What I am trying to achieve is, to run whichcolour through data.py and it will return/ print out whatever is in that list.

I know print(access.Japan[1]) works.. It returns cow.

How should the print statement be written such that it gives me the same result?

jake wong
  • 4,909
  • 12
  • 42
  • 85

1 Answers1

0

Use a dictionary.

access.py

countries = {
    'Japan': ['brown', 'cow', 'around'],
    'Korea': ['black', 'chicken', '344'],
    'China': ['grey', '3411', 'leaf'],
    'Indonesia': ['red', 'green', '']
}

data.py

from access import countries

def whichcolour(country, countries):
    print('{} has the color {}'.format(country, countries[country][0]))

for country in countries:
    whichcolour(country, countries)

output:

Japan has the color brown
Korea has the color black
China has the color grey
Indonesia has the color red

I'm not 100% sure what you want to do (there are two colors for Indonesia) but this should get you started.

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • Speaking of dictionaries, why not just use JSON altogether? – Eddo Hintoso Feb 21 '16 at 09:59
  • @EddoHintoso Or just a nested dictionary, such that you could access `countries['Japan']['color']`. I don't know what names would be suitable as keys for the other values, so I leave that for the OP. – timgeb Feb 21 '16 at 10:00
  • Fair enough. The answer would be better if you explained that Python (along with many other languages) operate with zero-based indexing. It was why the OP failed to access the color element by accidentally selecting the 2nd element. – Eddo Hintoso Feb 21 '16 at 10:04
  • I'm not too sure what JSON is.. I'm still really new to python. But this code that @timgeb wrote works! Thanks – jake wong Feb 21 '16 at 10:05
  • @jakewong also see http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python – timgeb Feb 21 '16 at 10:05