[英]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. 如果希望通过其关联的字符串(在本例中为“ VISA”)检索CreditCard对象,则应将该字符串设置为键,将对象设置为值,而不是相反。 Your dict
should look like this, 你的dict
应该像这样,
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. 如果同一字符串有多个对象,则该值可以是这些对象的list
。
frozenset
is not a dict
. frozenset
不是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. 从dict
创建frozenset
集只会创建包含该字典所有键的集合。 Why do you need it anyway? 为什么仍然需要它?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.