[Tutor] Fwd: Re: would someone please explain this concept to me

Alan Gauld alan.gauld at yahoo.co.uk
Wed Jun 5 14:45:33 EDT 2019


> That is why I was going to use g.blank-feed as the template, 
> assign that to d["feed 1's link"] then just update the feed part.

The simplest way is just to assign a new blank dictionary. Don;t assign
the same dictionary to each feed. (Incidentally your description above
is much clearer than the one you initially posted!)

feeds[link] = {key1:value1, key2:value2}

If you need to pre-populate the dictionary with many values when
you assign it (or need to compute  the values) I'd recommend
writing a small function that creates a new dictionary,
and adds the values then returns the dictionary.

Or maybe, better still, use a class and populate the feeds
dictionary with instances of the class.

class Feed:
   def __init__(self, val1=default1, val2=default2, val3=default3):
       self.key1 = val1
       self.key2 = val2
       self.key3 = val3

feeds[link1] = Feed(v1,v2,v3)
feeds[link2] = Feed()   # use default values

After all that's exactly what a class is - a template for an object.

What you definitely don't want to do is what you have been
doing and assigning the same single dictionary object to each
link entry.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list