dict order

cokofreedom at gmail.com cokofreedom at gmail.com
Wed Jun 18 06:35:15 EDT 2008


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



More information about the Python-list mailing list