Looking Up Postage by Country
In this lesson, you looked up the postage for order 1042 by a key held in a variable, and ported Marta’s rates table.
- The country comes from Iris’s address, cut down to the two fields this step needs, so the key
is in a variable. Python’s
RATES[country]isRATES[country]in JavaScript too: the brackets use the variable’s value. - Ported the way the order was, with the quotes off the keys, the table keeps
HOME_COUNTRYbare, as it was in Python. The port stops withTypeError: Cannot read properties of undefined (reading 'toFixed'): the lookup gaveundefined, because in JavaScript a key that isn’t there givesundefinedinstead of raising aKeyError. - Logged on its own, the table has a key called
HOME_COUNTRYand noGB. In an object literal, a bare key is always the key’s own name, as the order’sid: 1042made a key calledid. It’s the name you’d write after a dot, because an object is also a record:order.idreads the key thatid: 1042wrote. - Python reads a dict literal differently: a bare word there is a variable, so Python looks up
HOME_COUNTRYand uses its value, and the dict prints with'GB'first. The same line means the value in Python and the name in JavaScript. - To use a variable’s value as a key, wrap it in brackets inside the literal:
[HOME_COUNTRY]: 3.2, a computed property name. The brackets work out what’s inside and use the result, as Python’s bare word did. - Brackets mean “the value of this”, whether you read a key or write one in a literal. Dots and
bare keys mean “this name”, as a dot does on any Python object, so
RATES.countrylooks for a key calledcountryand givesundefined. Write a dot when you know the key as you write the code, as inaddress.country, and brackets when the key comes from data.
Here’s Marta’s Python step:
HOME_COUNTRY = "GB"
RATES = {
HOME_COUNTRY: 3.20,
"IE": 7.50,
"DE": 8.90,
"US": 14.50,
"ROW": 16.50,
}
address = {"city": "Leeds", "country": "GB"}
country = address["country"]
rate = RATES[country]
print(f"Postage: £{rate:.2f}")