简体   繁体   中英

Dictionary with multiple items in Python

I'm trying to setup and access a dictionary with multiple keys in Python.

#province, [shipping cost, valid postal codes]

provinceShipping = {"AB":[12,"A"],"BC":[12,"B"],"MB":[12,"M","L","K"]}

x = (input("province ")).upper()
y = (input("first letter of postal code ")).upper()
if x in provinceShipping:
access the cost and valid postal codes

Basically what I want to do is use a dictionary to contain the province, a shipping cost and valid postal codes. How do I access the postal codes after the cost? Some provinces also have more than one valid postal code such as "MB" in the above example. Is there a better way to do this?

In order to get the postal code of all the items, do:

for province, (shipping_cost, *postal_code) in provinceShipping.items():
    print('Province: ' ,province, 'Shipping Cost', shipping_cost, ' Postal Code: ', postal_code)

# prints:
Province:  MB Shipping Cost 12  Postal Code:  ['M', 'L', 'K']
Province:  BC Shipping Cost 12  Postal Code:  ['B']
Province:  AB Shipping Cost 12  Postal Code:  ['A']

For one particular province, you can do:

>>> provinceShipping['MB'][1:]   # For 'MB' province
['M', 'L', 'K']

If in all cases the first element in the value list of each key in the dictionary will be cost and the rest will ALWAYS be postal codes then you can use this:

if x in provinceShipping:
    print "cost: " ,  provinceShipping[x][0]
    print "post codes: " , provinceShipping[x][1:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM