[Tutor] unordered and ordered defaultdict(set)

Dinesh B Vadhia dineshbvadhia at hotmail.com
Thu Oct 30 23:01:15 CET 2008


Here is an interesting result with defaultdict(set). This program creates 2 dictionaries of sets with the first dictionary containing 10 elements per set and the second containing 25 elements.  You'll see the sets in the first dictionary are unordered and in the second they are ordered.  

import random
from collections import defaultdict

a = defaultdict(set)

l = [10, 25, 35]
for last in l:
        for s in xrange(0, 10, 1):
            for t in xrange(0, last, 1):
                    r = random.randint(1,101)
                    a[s].add(r)

            for r in a.items():
                    print r
    print


(0, set([36, 38, 12, 77, 15, 49, 19, 23, 61, 95]))
(1, set([1, 34, 3, 37, 38, 11, 80, 17, 59]))
(2, set([67, 37, 11, 79, 81, 90, 60, 62, 69]))
(3, set([34, 98, 44, 66, 13, 81, 53, 55, 25, 79]))
(4, set([98, 101, 81, 14, 47, 49, 53, 88, 92, 61]))
(5, set([49, 72, 40, 50, 52, 89, 57, 60, 30, 31]))
(6, set([65, 98, 39, 80, 51, 87, 26, 91]))
(7, set([33, 6, 42, 16, 85, 56, 58, 21, 63]))
(8, set([64, 33, 35, 93, 80, 21, 24, 90, 47, 58]))
(9, set([3, 73, 74, 44, 77, 17, 35, 21, 54, 89]))

(0, set([4, 12, 15, 16, 18, 19, 21, 22, 23, 24, 26, 28, 30, 36, 38, 41, 45, 46, 49, 52, 61, 64, 74, 77, 80, 85, 87, 89, 91, 94, 95, 96]))
(1, set([1, 3, 8, 10, 11, 17, 28, 30, 32, 33, 34, 35, 37, 38, 39, 40, 48, 50, 55, 56, 58, 59, 62, 79, 80, 81, 90, 92, 100]))
(2, set([8, 9, 11, 22, 34, 37, 41, 48, 49, 53, 57, 60, 61, 62, 65, 67, 69, 71, 73, 74, 75, 76, 79, 80, 81, 90, 94, 95, 98]))
(3, set([3, 7, 9, 12, 13, 17, 18, 23, 24, 25, 27, 31, 34, 44, 53, 54, 55, 59, 66, 67, 69, 76, 79, 81, 88, 89, 94, 95, 98, 101]))
(4, set([8, 14, 17, 19, 20, 25, 32, 33, 34, 37, 43, 46, 47, 49, 53, 58, 59, 61, 63, 68, 69, 71, 81, 86, 88, 89, 92, 95, 96, 98, 101]))
(5, set([2, 7, 10, 14, 20, 24, 27, 30, 31, 38, 39, 40, 43, 44, 46, 49, 50, 52, 57, 59, 60, 62, 64, 67, 68, 70, 72, 76, 79, 83, 85, 86, 89, 90]))
(6, set([1, 2, 3, 6, 9, 16, 18, 23, 26, 30, 32, 34, 37, 39, 43, 47, 49, 50, 51, 63, 65, 80, 87, 91, 96, 97, 98, 99]))
(7, set([3, 5, 6, 7, 9, 14, 15, 16, 17, 21, 24, 28, 33, 34, 42, 44, 51, 53, 56, 58, 61, 63, 69, 74, 76, 84, 85, 87, 92]))
(8, set([4, 5, 6, 8, 9, 17, 20, 21, 24, 28, 33, 35, 38, 47, 55, 58, 59, 64, 66, 69, 70, 71, 77, 79, 80, 82, 86, 87, 90, 93, 100, 101]))
(9, set([3, 5, 6, 12, 14, 17, 19, 20, 21, 23, 35, 43, 44, 46, 47, 50, 54, 55, 58, 62, 63, 68, 71, 73, 74, 76, 77, 87, 89, 91, 92]))

Unless my eyes are squiffy the 2nd dictionary of sets appears ordered.  I've run it with other numbers > 25 and continue to get ordered sets but anything < 25 results in unordered sets.  A feature or a bug?

Dinesh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20081030/e0921e8a/attachment.htm>


More information about the Tutor mailing list