簡體   English   中英

字典中的追加列表

[英]Appending list in a dict of dicts

我想念什么? 我有一個dict的dict(它是動態創建的),如下所示:

googlers = 3
goog_dict = {}
dict_within = {'score':[], 'surprise':''}
for i in xrange(googlers):
   name = "goog_%s" %i
   goog_dict[name] = dict_within 

現在我要添加一些數據:

tot =[23,22,21] 
best_res = 8


for i in xrange(len(tot)):

   name = "goog_%s" %i
   print name
   rest = tot[i] - best_res
   if rest % 2 == 0:
      trip = [best_res, rest/2, rest/2]

   elif rest % 2 != 0:
      rest_odd = rest / 2
      fract_odd = rest - rest_odd
      trip = [best_res, rest_odd, fract_odd]

   if (max(trip) - min(trip)) == 2:
      surpr_state = True
   elif (max(trip) - min(trip)) < 2:
      surpr_state = False

   goog_dict[name]['score'].append(trip)
   goog_dict[name]['surprise'] = surpr_state

我希望我的輸出是:

{'goog_2': {'surprise': True, 'score': [8, 7, 8]}, 'goog_1':{'surprise': True, 'score':  [8, 7, 7]}, 'goog_0': {'surprise': True, 'score': [8, 6, 7]}}

但是我得到的是:

{'goog_2': {'surprise': True, 'score': [[8, 7, 8], [8, 7, 7], [8, 6, 7]]}, 'goog_1':{'surprise': True, 'score': [[8, 7, 8], [8, 7, 7], [8, 6, 7]]}, 'goog_0': {'surprise': True, 'score': [[8, 7, 8], [8, 7, 7], [8, 6, 7]]}}

那么,為什么將清單trip附加到所有字典而不是僅附加到具有當前name字典?

編輯:

如我所猜。 goog_dict的每個元素都是相同的元素。 閱讀一些有關關系的信息,因為它可能真的很有幫助。

將代碼更改為:

goog_dict = {}
googlers = 3
for i in xrange(googlers):
   name = "goog_%s" %i
   dict_within = {'score':[], 'surprise':''}
   goog_dict[name] = dict_within 

現在應該可以了。

還要看這個例子。 就是這樣,您的情況就是如此。

>>> a = []
>>> goog_dict = {}
>>> goog_dict['1'] = a
>>> goog_dict['2'] = a
>>> goog_dict['3'] = a
>>> goog_dict
{'1': [], '3': [], '2': []}
>>> goog_dict['1'].append([1, 2, 3])
>>> goog_dict
{'1': [[1, 2, 3]], '3': [[1, 2, 3]], '2': [[1, 2, 3]]}

這是一個很常見的錯誤。

嘗試這個:

googlers = 3
goog_dict = {}
for i in xrange(googlers):
   name = "goog_%s" %i
   goog_dict[name] = {'score':[], 'surprise':''}

字典中的"score"值在任何地方都指向相同的列表 ,因此您會看到效果。 嘗試將構建字典的代碼粘貼到此python代碼可視化工具中,以查看會發生什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM