I am trying to initialize a dictionary as a attribute in my object and trying to use defaultdict. Somehow, it works on Mac not Windows. What I want is:
1 {'1':[], '2':[]}
2 {'1':[], '2':[]}
Here is what I ve done so far.
class A:
def __init__(self, id):
self.id = id
self.x = self.y
@property
def y(self):
ref = defaultdict(list)
ls = ['1', '2']
for i in ls:
ref[i] = []
return ref
def __str__(self):
return f'{self.id}, {self.x}'.format(self=self)
def main():
for i in range(2):
me = A(i)
print(me)
if __name__ == '__main__':
main()
Error message I'm having is:
KeyError: "'23'"
or some other numbers and varies every time. The self.y
function works when I am just directly accessing it. Like:
for i in range(2):
me = A(i)
print(me.y)
Of course, before that I set:
class A:
def __init__(self, id):
self.id = id
self.x = []
then
for i in range(2):
me = A(i)
print(me)
I get
1 []
2 []
but I want
1 {'1':[]}
2 {'2':[]}
so I can add some values in dictionary values.
What am I doing wrong? It seems there is a problem in return values when I sign {}
instead of []
. Is there a way to figure out or work around it?
You are using both f""
and str.format
, so you do formatting twice. str.format
interprets 1 {'1':[]}
as template string and tries to expand '1'
, thus a KeyError
.
Thanks great responses and recommendations. Yes, I am sure many of you see 'weird' stuff in my codes because I do not fully explained the purposes. Yes, I should not use defaultdict instead of a simple dict. Yes, I was using f'' also.format(). Thanks for the lesson.
What works across platform is could be simple but want your feedback. '''
class A:
def __init__(self, x):
self.x = x # id
self.y = {} # key = days, value = activities
def make_day(self):
''' each inst accepts random days and days have random activities'''
random_days = ['sorted','string','days','sampled','from','week']
for each_day in random_days:
self.y[each_day] = []
return self.y
def __str__(self):
return f'%d, %s'%(self.x, self.y)
def main(): for i in range(2): a = A(i) a.make_day() print(a) if name == ' main ': main()
0, {'sorted': [], ..., 'week': []} 1, {'sorted': [], ..., 'week': []}
'''
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.