Reputation: 493
I have only been working with python for a few months, so sorry if I am asking a stupid question. I am having a problem calling a dictionary name using a variable.
The problem is, if I use a variable to call a dictionary & [] operators, python interprets my code trying to return a single character in the string instead of anything within the dictionary list.
To illustrate by an example ... let's say I have a dictionary list like below.
USA={'Capital':'Washington',
'Currency':'USD'}
Japan={'Capital':'Tokyo',
'Currency':'JPY'}
China={'Capital':'Beijing',
'Currency':'RMB'}
country=input("Enter USA or JAPAN or China? ")
print(USA["Capital"]+USA["Currency"]) #No problem -> WashingtonUSD
print(Japan["Capital"]+Japan["Currency"]) #No problem -> TokyoJPY
print(China["Capital"]+China["Currency"]) #No problem -> BeijingRMB
print(country["Capital"]+country["Currency"]) #Error -> TypeError: string indices must be integers
In the example above, I understand the interpreter is expecting an integer because it views the value of "country" as a string instead of dictionary... like if I put country[2] using Japan as input (for example), it will return the character "p". But clearly that is not what my intent is.
Is there a way I can work around this?
Upvotes: 2
Views: 5336
Reputation: 8547
Disclaimer: Any other way of doing it is definitely better than the way I'm about to show. This way will work, but it is not pythonic. I'm offering it for entertainment purposes, and to show that Python is cool.
USA={'Capital':'Washington',
'Currency':'USD'}
Japan={'Capital':'Tokyo',
'Currency':'JPY'}
China={'Capital':'Beijing',
'Currency':'RMB'}
country=input("Enter USA or Japan or China? ")
print(USA["Capital"]+USA["Currency"]) #No problem -> WashingtonUSD
print(Japan["Capital"]+Japan["Currency"]) #No problem -> TokyoJPY
print(China["Capital"]+China["Currency"]) #No problem -> BeijingRMB
# This works, but it is probably unwise to use it.
print(vars()[country]["Capital"] + vars()[country]['Currency'])
This works because the built-in function vars
, when given no arguments, returns a dict of variables (and other stuff) in the current namespace. Each variable name, as a string, becomes a key in the dict.
But @tom's suggestion is actually a much better one.
Upvotes: 1
Reputation: 19153
You should put your countries themselves into a dictionary, with the keys being the country names. Then you would be able to do COUNTRIES[country]["Capital"]
, etc.
Example:
COUNTRIES = dict(
USA={'Capital':'Washington',
'Currency':'USD'},
Japan={'Capital':'Tokyo',
'Currency':'JPY'},
...
)
country = input("Enter USA or Japan or China? ")
print(COUNTRIES[country]["Capital"])
Upvotes: 2