[Tutor] Q about .join() Thanks!

Alan Gauld alan.gauld at yahoo.co.uk
Mon Feb 13 20:31:57 EST 2017


On 13/02/17 18:34, SIJIA CHEN wrote:
> I find out that the outcome for using .join() on a dictionary is 
> totally different than it using on list or string.

Not really, it just looks like that :-)

> 
>                   >>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
>                   >>> print ':'.join(seq4)
>                   boy:good:doiido:hello
> So my question is why the outcome doesn't show sequentially

That's because dictionaries are not stored sequentially and the
order of retrieval is not guaranteed - it can even change
during the execution of a program so you should never
depend on it. That's because dictionaries are optimised
for random access via the keys not to be iterated over.

You can sort the keys and then pull the values and that will
give you a guaranteed order but simply printing the dictionary
(or joining it as you did) is not reliable.

I've a vague memory that recent versions of Python may have
a special dictionary type that does return items in the order
they were inserted, but I may be mixing that up with
another language... Hopefully someone else can provide
a steer there.

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