dict order

Lie Lie.1296 at gmail.com
Wed Jun 18 13:11:31 CEST 2008


On Jun 18, 5:35 pm, cokofree... at gmail.com wrote:
> On Jun 18, 12:32 pm, cokofree... at gmail.com wrote:
>
>
>
> > On Jun 18, 11:22 am, Robert Bossy <Robert.Bo... at jouy.inra.fr> wrote:
>
> > > Hi,
>
> > > I wish to know how two dict objects are compared. By browsing the
> > > archives I gathered that the number of items are first compared, but if
> > > the two dict objects have the same number of items, then the comparison
> > > algorithm was not mentioned.
>
> > > Note that I'm not trying to rely on this order. I'm building a
> > > domain-specific language where there's a data structure similar to
> > > python dict and I need an source of inspiration for implementing
> > > comparisons.
>
> > > Thanks
> > > RB
>
> > I'm a little confused as to what you want. Are you asking whether two
> > dictionary objects have the same keys AND values, or just the Keys?
>
> > As dictionaries are unordered the best technique is to go through one
> > dictionary and take out a key, then see if that key exists in the
> > other dictionary, and if so do they share the same values.
>
> > # untested 2.5
> > for keys in dict_one.items():
> >   if keys in dict_two:
> >     if dict_one[keys] != dict_two[keys]:
> >       # values are different
> >   else:
> >     # key is not present
>
> > This probably isn't the most efficient way, but can quickly find
> > differences...
>
> Whoops
>
> for keys, values in dict_one.items():
>   if keys in dict_two:
>     if values == dict_two[keys]:
>
> should also work...

Whoops, I think I misunderstood the question. If what you're asking
whether two dictionary is equal (equality comparison, rather than
sorting comparison). You could do something like this:

a = [...]
b = [...]

s = set()

for bk, bv in b.iteritems():
    s.add((bk, bv))

for ak, av in a.iteritems():
    if not((ak, av) in s):
        print 'Difference Found!'



More information about the Python-list mailing list