简体   繁体   中英

Appending list in a dict of dicts

What Am I missing? I'm having a dict of dicts (which was created on the fly) like this:

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

Now I want to add some data:

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

I'd expect my output to be:

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

But what I get is this:

{'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]]}}

So why is the list trip append to all dicts instead of only the one with the current name ?

EDIT:

As i guessed. Each element of your goog_dict is the same element. Read a little about relations, as it might be really helpful.

Change your code into:

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

And now it should be ok.

Also take a look at this example. That's exactly, what happened in your case.

>>> 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]]}

This one is quite a common mistake.

Try this:

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

The value of "score" in the dict pointed to the same list everywhere, hence the effect you saw. Try to paste your dict-building code into this python code visualizer to see what happens.

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