简体   繁体   中英

Create dictionaries of objects in python

I've created a dict of objects (creditcards):

class CreditCard:

    def __init__(self,number,expire_date_month,expire_date_year,CVC):
        self.number=number
        self.expire_date_month=expire_date_month
        self.expire_date_year=expire_date_year
        self.CVC=CVC

credit_cards={CreditCard('1000000000000000','3','2011','111'):'VISA'}
credit_cards_frozen=frozenset({CreditCard('1000000000000000','3','2011','111'):'VISA'})

but I have an error while executing these commands:

print credit_cards['VISA'] #KeyError: 'VISA'
print credit_cards_frozen['VISA'] #TypeError: 'frozenset' object is not subscriptable

What's wrong with my code?

I think there are two things that are wrong with your code.

  • If you want the CreditCard object to be retrieved by its associated string ('VISA' in this case), you should make the string the key and the object the value and not the other way around. Your dict should look like this,

    credit_cards={'VISA':CreditCard('1000000000000000','3','2011','111')}

    If there are multiple objects for the same string, the value can be a list of those objects.

  • frozenset is not a dict . It does not store (key, value) paired data. Creating a frozenset from a dict just creates a set with all the keys of the dict. Why do you need it anyway?

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