[issue34514] assertEqual doesn't use maxDiff when comparing dictionaries

2020-10-20 Thread Irit Katriel


Change by Irit Katriel :


--
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34514] assertEqual doesn't use maxDiff when comparing dictionaries

2020-09-17 Thread Irit Katriel


Irit Katriel  added the comment:

I think this can be closed as not a bug, unless Victor can clarify with an 
example script why there is an issue.

--
nosy: +iritkatriel

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34514] assertEqual doesn't use maxDiff when comparing dictionaries

2018-08-27 Thread Prudvi RajKumar Maddala


Prudvi RajKumar Maddala  added the comment:

I see that maxDiff is applied correctly when comparing dictionaries. I don't 
think that's an issue.

--

___
Python tracker 
<https://bugs.python.org/issue34514>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34514] assertEqual doesn't use maxDiff when comparing dictionaries

2018-08-27 Thread Karthikeyan Singaravelan


Karthikeyan Singaravelan  added the comment:

@victor I am little confused over the issue since you have said 
"`assertDictEqual()` "will be used by default to compare dictionaries in calls 
to assertEqual()" and "`maxDiff` doesn't apply to `assertEqual()` when 
comparing dictionaries" . Since assertDictEqual is used for assertEqual calls 
when they compare dictionaries I can see that maxDiff value is applied to the 
diffs. A script will be helpful here on the expected and actual output. The 
attached script I have used to check that the maxDiff value is applied.


$ ./python.exe ../backups/bpo34514.py


==
FAIL: test_assert_dict_equal_large_diff (__main__.Test_TestCase)
--
Traceback (most recent call last):
  File "../backups/bpo34514.py", line 59, in test_assert_dict_equal_large_diff
self.assertDictEqual(original, expected)
AssertionError: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, [726 chars]: 99} != 
{101: 101, 102: 102, 103: 103, 104: 104, 10[942 chars] 199}
Diff is 3347 characters long. Set self.maxDiff to None to see it.

==
FAIL: test_assert_dict_equal_small_diff (__main__.Test_TestCase)
--
Traceback (most recent call last):
  File "../backups/bpo34514.py", line 31, in test_assert_dict_equal_small_diff
self.assertDictEqual(original, expected)
AssertionError: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9} != {101: 
101, 102: 102, 103: 103, 104: 104, 10[42 chars] 109}
- {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
+ {101: 101,
+  102: 102,
+  103: 103,
+  104: 104,
+  105: 105,
+  106: 106,
+  107: 107,
+  108: 108,
+  109: 109}

==
FAIL: test_assert_equal_large_diff (__main__.Test_TestCase)
--
Traceback (most recent call last):
  File "../backups/bpo34514.py", line 45, in test_assert_equal_large_diff
self.assertEqual(original, expected)
AssertionError: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, [726 chars]: 99} != 
{101: 101, 102: 102, 103: 103, 104: 104, 10[942 chars] 199}
Diff is 3347 characters long. Set self.maxDiff to None to see it.

==
FAIL: test_assert_equal_small_diff (__main__.Test_TestCase)
--
Traceback (most recent call last):
  File "../backups/bpo34514.py", line 17, in test_assert_equal_small_diff
self.assertEqual(original, expected)
AssertionError: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9} != {101: 
101, 102: 102, 103: 103, 104: 104, 10[42 chars] 109}
- {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
+ {101: 101,
+  102: 102,
+  103: 103,
+  104: 104,
+  105: 105,
+  106: 106,
+  107: 107,
+  108: 108,
+  109: 109}

--
Ran 4 tests in 3.496s

FAILED (failures=4)


Thanks

--
Added file: https://bugs.python.org/file47764/bpo34514.py

___
Python tracker 
<https://bugs.python.org/issue34514>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34514] assertEqual doesn't use maxDiff when comparing dictionaries

2018-08-27 Thread Karthikeyan Singaravelan


Karthikeyan Singaravelan  added the comment:

@prudvinit 

Reference : 
https://docs.python.org/3.8/library/unittest.html#unittest.TestCase.maxDiff

> This attribute controls the maximum length of diffs output by assert methods 
> that report diffs on failure. It defaults to 80*8 characters. Assert methods 
> affected by this attribute are assertSequenceEqual() (including all the 
> sequence comparison methods that delegate to it), assertDictEqual() and 
> assertMultiLineEqual().

Thanks

--
nosy: +xtreak

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34514] assertEqual doesn't use maxDiff when comparing dictionaries

2018-08-26 Thread Prudvi RajKumar Maddala


Prudvi RajKumar Maddala  added the comment:

Hello Victor, can you tell me what is 'maxDiff'? Can you give me a simple 
example of expected output and actual output by taking a simple dictionary?

Thanks

--
nosy: +prudvinit

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue34514] assertEqual doesn't use maxDiff when comparing dictionaries

2018-08-26 Thread Victor Engmark


New submission from Victor Engmark :

According to the documentation `assertDictEqual()` "will be used by default to 
compare dictionaries in calls to assertEqual()." Great, since `maxDiff` applies 
to assertDictEqual(). However, `maxDiff` doesn't apply to `assertEqual()` when 
comparing dictionaries.

--
components: Tests
messages: 324140
nosy: Victor Engmark2
priority: normal
severity: normal
status: open
title: assertEqual doesn't use maxDiff when comparing dictionaries
type: behavior
versions: Python 3.6

___
Python tracker 
<https://bugs.python.org/issue34514>
___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue9132] Documentation for comparing dictionaries is out of date

2010-07-14 Thread Senthil Kumaran

Senthil Kumaran orsent...@gmail.com added the comment:

The patch was pretty good. Committed it in r82899 and r82900.
Thanks Eli for the patch  Terry for the review.

--
nosy: +orsenthil
resolution:  - fixed
stage: commit review - committed/rejected
status: open - closed

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue9132
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue9132] Documentation for comparing dictionaries is out of date

2010-07-12 Thread Eli Bendersky

Eli Bendersky eli...@gmail.com added the comment:

I agree with Terry's proposal. Here's a patch file for 
Doc/reference/expressions.rst that implements the change.

--
Added file: http://bugs.python.org/file17967/issue9132.2.patch

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue9132
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue9132] Documentation for comparing dictionaries is out of date

2010-07-12 Thread Terry J. Reedy

Terry J. Reedy tjre...@udel.edu added the comment:

Looks good to me. Thanks Eli.

--
stage: needs patch - commit review

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue9132
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue9132] Documentation for comparing dictionaries is out of date

2010-07-09 Thread Eli Bendersky

Changes by Eli Bendersky eli...@gmail.com:


--
nosy: +eli.bendersky

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue9132
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue9132] Documentation for comparing dictionaries is out of date

2010-07-04 Thread Terry J. Reedy

Terry J. Reedy tjre...@udel.edu added the comment:

On the 'patch' keyword: I thought the same as you (only for diff) until 
yesterday morning when Brett Cannon specifically told me that I should also set 
it for in-message text patches. This was in the context of him having not 
noticed for months (until I pinged him) that I had included a text patch in a 
message for an issue assigned to him, because he skims messages and looks for 
the keyword and other header changes. So until a 'higher' tracker authority 
tell me differently, I am following his direction. I am also highlighting the 
actual patch in the message to make it easy to find.


The current compare equal if and only if their sorted (key, value) lists 
compare equal. [4] was written when all objects were comparable and when dict 
== dict *was* written that way (according to [5]). The footnote was added to 
assure people that the new internal implementation was faster (ie, set 
comparison via hash lookup) than it once had been.

For a long time, that definition of dict equality has been invalid because it 
cannot be implemented that way; the definition is even more meaningless in 
Python3. So is footnote [4] saying that the meaningless definition is not the 
implementation. Both [4] and [5] are ancient fossils referring back to Python1. 

Without looking, I am confident that the actual implementation is O(1) if the 
dicts are unequal in size and an O(n) (key,value) set comparison if they are 
equal in size. My proposed revision is intended to imply that. Note that Python 
did not have sets when the sorted list definition was written. Also note that 
there is no footnote attached to set comparison (which once could have also 
been defined in terms of sorted lists).

Dicts are sets (of pairs), not unsorted lists (of pairs) and the current docs 
should reflect that.

The language def makes no guarantees about implementation efficiency.  In 13 
years of watching c.l.p/python-list, I have not seen any particular concern 
about dict comparison that would warrant special notice. Rather, people worry 
about the big-O behavior of building large lists and dicts of millions of 
items. The sometimes need persuading that construction is more efficient than 
they might imagine. That is about the only thing I can think of for which an 
efficiency note might be a good idea.


'Comparisons other than equality testing' include 'is' and 'in'. They work for 
dictionaries as expected, which is to say, as identify and containment testing, 
as for everything else. They do not raise TypeError. So the statement that 
implies that they do is not correct.


PATCH REVISION: The suggested Order comparision raise TypeError. has spelling 
and agreement errors in 'comparision' and should be Order comparisons raise 
TypeError.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue9132
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue9132] Documentation for comparing dictionaries is out of date

2010-07-04 Thread Éric Araujo

Éric Araujo mer...@netwok.org added the comment:

Thanks for the explanation of the patch keyword. Its description (click on 
“Keywords”) is indeed generic (“contains patch”), 
http://www.python.org/dev/patches/ should probably say it too.

I don’t have enough knowledge to make a useful comment on the rest of your 
reply. Other people most certainly will.

I think two of my remarks are not addressed by your reply:
- Is the term “order comparisons” used in the doc? If not, its
meaning is non-obvious, and I’d like to find something clearer.
- Testing with “is” is called identity testing, “in” is membership or 
containement testing. Where are they called “comparisons”?

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue9132
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue9132] Documentation for comparing dictionaries is out of date

2010-07-04 Thread Terry J. Reedy

Terry J. Reedy tjre...@udel.edu added the comment:

I intentionally began my first post with The RefMan section is 5.9. 
Comparisons. Look there, particularly the definition of comp_operator.

In this context, I think 'order comparison' is pretty clearly a comparison with 
an order operator, '' and ''. But fine with me if the editor want to list 
them explicitly.

POSSIBLE PATCH ADDITION: ('', '=', '', '=')

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue9132
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue9132] Documentation for comparing dictionaries is out of date

2010-07-03 Thread Terry J. Reedy

Terry J. Reedy tjre...@udel.edu added the comment:

The RefMan section is 5.9. Comparisons. The 3.x docs are by design pretty much 
free of 2.x references. Which is to say, they are a fresh start with 3.0 as the 
base. So I would also remove footnote 5. Footnote 4 is currently needed because 
the text suggests something that is not true. Instead fix the text and remove 4.


 I verified both behavior claims with 3.1:
 d1 = {1+1j: 2, 1+2j: 3}
 d2 = {1+1j: 2, 1+2j: 3}
 d1 == d2
True
 d1  d2
Traceback (most recent call last):
  File pyshell#14, line 1, in module
d1  d2
TypeError: unorderable types: dict()  dict()

PATCH suggestion: Replace the current entry with

Mappings (dictionaries) compare equal if and only if they have the same key, 
value) pairs. Order comparision raise TypeError.

Remove footnotes 4 and 5.

Comparisons other than equality testing raise a TypeError.
is not quite correct because 'comparisons' include 'is' and 'in' which do work 
as expected.

--
keywords: +patch
nosy: +tjreedy
type:  - behavior

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue9132
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue9132] Documentation for comparing dictionaries is out of date

2010-07-03 Thread Éric Araujo

Éric Araujo mer...@netwok.org added the comment:

Thanks for tackling this Terry. Did you include a patch, i.e. a diff
file? If not, the “patch” keyword does not apply, IIUC. Plain English
suggestions are helpful but they’re reviewed in a different way than a diff.

“The 3.x docs are by design pretty much free of 2.x references. Which is
to say, they are a fresh start with 3.0 as the base.“
True. That said, I would leave footnote 4, since it provides a useful
information for people caring about performance, and may interest them
in digging into the details of the implementation. It may need an
explicit mention “in CPython”, though.

“So I would also remove footnote 5.”
I don’t know. It’s an historical note about an implementation detail; it
does no harm (apart maybe taking space for no gain) and may be
interesting to some people. Does a core dev have an opinion on that
(Georg?).

“Footnote 4 is currently needed because the text suggests something that
is not true.”
I can’t say if the text is inaccurate or just difficultly readable.

“Mappings (dictionaries) compare equal if and only if they have the
same key, value) pairs. Order comparision raise TypeError.”
I’ll even say “the same (key, value) pairs, irregardless of their
order”. Is the term “order comparisons” used in the doc? If not, its
meaning is non-obvious, and I’d like to find something clearer.

“Comparisons other than equality testing raise a TypeError. is not
quite correct because 'comparisons' include 'is' and 'in' which do work
as expected.”
I thought “is” was clearly identity and “in” membership or containement
testing in the doc. Can you support your claim?

Cheers

--
nosy: +merwok

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue9132
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue9132] Documentation for comparing dictionaries is out of date

2010-06-30 Thread Daniel Stutzbach

New submission from Daniel Stutzbach dan...@stutzbachenterprises.com:

reference/expressions.html#notin reads:

Mappings (dictionaries) compare equal if and only if their sorted (key, value) 
lists compare equal. [4] Outcomes other than equality are resolved 
consistently, but are not otherwise defined. [5]

However, the last sentence is no longer true.  I suggest changing the last 
sentence to:

Comparisons other than equality testing raise a TypeError.

I think the footnote [5] is sufficiently historical that it could be removed as 
well.  Alternately, it could be updated to read, In older versions of Python, 
outcomes other than equality were resolved consistently but were not otherwise 
defined.

--
assignee: d...@python
components: Documentation
messages: 109009
nosy: d...@python, stutzbach
priority: normal
severity: normal
stage: needs patch
status: open
title: Documentation for comparing dictionaries is out of date
versions: Python 3.1, Python 3.2

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue9132
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue9132] Documentation for comparing dictionaries is out of date

2010-06-30 Thread Daniel Stutzbach

Changes by Daniel Stutzbach dan...@stutzbachenterprises.com:


--
keywords: +easy

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue9132
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue9132] Documentation for comparing dictionaries is out of date

2010-06-30 Thread Alexander Belopolsky

Alexander Belopolsky belopol...@users.sourceforge.net added the comment:

Reference to sorted (key, value) lists is a bit misleading as well.  Dicts' 
equality is defined even if key or values are not orderable.

--
nosy: +belopolsky

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue9132
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: comparing dictionaries

2008-05-08 Thread Terry Reedy

Miki [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
Hello,

 I want to compare two dicts that should have identical info just in a
 different data structure. The first dict's contents look like this. It
 is authoritative... I know for sure it has the correct key value pairs:

 {'001' : '01'}

 The second dict's contents are like this with a tuple instead of a
 string for the key:

 {('This is one', '001'): '01'}

 Pseudo Code:
 for key, value in first_dict.iteritems():
 # How do I do the following line?
 if key not in second_dict or if it is, but has has the wrong value,
 then let me know

Does this work for you?

for key,value in second_dict.iteritems():
  try:
if first_dict[key(1)] == value:
return True
else:
return False:
  except KeyError:
return False

tjr 



--
http://mail.python.org/mailman/listinfo/python-list


comparing dictionaries

2008-05-07 Thread brad
I want to compare two dicts that should have identical info just in a 
different data structure. The first dict's contents look like this. It 
is authoritative... I know for sure it has the correct key value pairs:


{'001' : '01'}

The second dict's contents are like this with a tuple instead of a 
string for the key:


{('This is one', '001'): '01'}

Pseudo Code:
for key, value in first_dict.iteritems():
  # How do I do the following line?
  if key not in second_dict or if it is, but has has the wrong value, 
then let me know


--
http://mail.python.org/mailman/listinfo/python-list


Re: comparing dictionaries

2008-05-07 Thread cokofreedom
On May 7, 4:08 pm, brad [EMAIL PROTECTED] wrote:
 I want to compare two dicts that should have identical info just in a
 different data structure. The first dict's contents look like this. It
 is authoritative... I know for sure it has the correct key value pairs:

 {'001' : '01'}

 The second dict's contents are like this with a tuple instead of a
 string for the key:

 {('This is one', '001'): '01'}

 Pseudo Code:
 for key, value in first_dict.iteritems():
# How do I do the following line?
if key not in second_dict or if it is, but has has the wrong value,
 then let me know

Well

for k, v in first_dict.items():
  if k not in second_dict or k in second_dict and k[v] !=
second_dict[k]:
let you know?
--
http://mail.python.org/mailman/listinfo/python-list


Re: comparing dictionaries

2008-05-07 Thread Carsten Haese

brad wrote:
I want to compare two dicts that should have identical info just in a 
different data structure. The first dict's contents look like this. It 
is authoritative... I know for sure it has the correct key value pairs:


{'001' : '01'}

The second dict's contents are like this with a tuple instead of a 
string for the key:


{('This is one', '001'): '01'}


It looks like extracting key[1] from each key of the second dictionary 
should yield the keys of the first dictionary. If that is the case, then 
the following should do it:


d1 = {'001':'01', '002':'02'}
d2 = {('This is one', '001'): '01', ('This is two', '002'): '02'}

if d1 == dict( zip( (k[1] for k in d2.keys()), d2.values() ) ):
print They're 'equal'.

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: comparing dictionaries

2008-05-07 Thread Arnaud Delobelle
brad [EMAIL PROTECTED] writes:

 I want to compare two dicts that should have identical info just in a
 different data structure. The first dict's contents look like this. It
 is authoritative... I know for sure it has the correct key value
 pairs:

 {'001' : '01'}

- refdict


 The second dict's contents are like this with a tuple instead of a
 string for the key:

 {('This is one', '001'): '01'}

- multidict


 Pseudo Code:
 for key, value in first_dict.iteritems():
   # How do I do the following line?
   if key not in second_dict or if it is, but has has the wrong value,
 then let me know

I think it's best to iterate over items of the second dictionary
first.  I am assuming that a key can be repeated in the second
dictionary, otherwise it could be a bit simpler:

missing_keys = set(first_dict)
for keys, val in second_dict.iteritems():
for key in keys:
missing_keys.discard(key)
if first_dict.get(key, val) != val:
print wrong value for, key, 'in', keys
if missing_keys:
print 'some keys are missing:', ',',join(remaining) 

-- 
Arnaud
--
http://mail.python.org/mailman/listinfo/python-list


Re: comparing dictionaries

2008-05-07 Thread Miki
Hello,

 I want to compare two dicts that should have identical info just in a
 different data structure. The first dict's contents look like this. It
 is authoritative... I know for sure it has the correct key value pairs:

 {'001' : '01'}

 The second dict's contents are like this with a tuple instead of a
 string for the key:

 {('This is one', '001'): '01'}

 Pseudo Code:
 for key, value in first_dict.iteritems():
    # How do I do the following line?
    if key not in second_dict or if it is, but has has the wrong value,
 then let me know
def cmp_dicts(first, second):
return sorted(first.iteritems()) == \
   sorted(((k[1], v) for k, v in second.iteritems()))

Google for DSU (Decorate-Sort-Undecorate)

HTH,
--
Miki [EMAIL PROTECTED]
http://pythonwise.blogspot.com


--
http://mail.python.org/mailman/listinfo/python-list


comparing dictionaries to find the identical keys

2007-12-28 Thread Beema shafreen
hi everybody ,
i need to compare two dictionary's key. I have written a script
gene_symbol = {}
probe_id = {}
result = {}
def getGene(fname):
fh = open(fname , 'r')
for line in fh:
yield line
fh.close()
for line in getGene(symbol_hu133):
data1= line.strip().split('#')
probe_give = data1[0].strip()
gene_give = data1[1].strip()
gene_symbol[probe_give] = gene_give
#print gene_symbol.keys()
for line in getGene(gds1428.csv):
data = line.strip().split(',')
probe_get = data[0].strip()
probe_id[probe_get] = data
if gene_symbol.keys() == probe_id.keys():
print gene_symbol.keys(), probe_id.values()


can anybody show me  the error I make here ,while comparing the keys of two
dictionaries so that i print the values of the  dictionaries whoes Keys are
Identical
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: comparing dictionaries to find the identical keys

2007-12-28 Thread km
Hi

On Dec 28, 2007 4:55 PM, Beema shafreen [EMAIL PROTECTED] wrote:

 hi everybody ,
 i need to compare two dictionary's key. I have written a script
 gene_symbol = {}
 probe_id = {}
 result = {}
 def getGene(fname):
 fh = open(fname , 'r')
 for line in fh:
 yield line
 fh.close()
 for line in getGene(symbol_hu133):
 data1= line.strip().split('#')
 probe_give = data1[0].strip()
 gene_give = data1[1].strip()
 gene_symbol[probe_give] = gene_give
 #print gene_symbol.keys()
 for line in getGene(gds1428.csv):
 data = line.strip().split(',')
 probe_get = data[0].strip()
 probe_id[probe_get] = data
 if gene_symbol.keys() == probe_id.keys():
 print gene_symbol.keys(), probe_id.values()


 can anybody show me  the error I make here ,while comparing the keys of
 two dictionaries so that i print the values of the  dictionaries whoes Keys
 are Identical

 Remember that ur looking for commonly occuring keys between the two
dictionaries.
And dictionary.keys() generates a 'list' of keys in that dictionary.
So, u r comparing a list with another  in an if construct and printing the
same which is not what u want to do.
Ideally u should iterate over a list of items and check out if it is present
or not in the other list and then print corresponding values.

Alternately this can also be done with sets module by converting the list
into a set object and do a  simple intersection of the two sets, by which u
get the commonly occuring items.

HTH
KM

 --
 http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: comparing dictionaries to find the identical keys

2007-12-28 Thread Christian Heimes
Beema shafreen wrote:
 hi everybody ,
 i need to compare two dictionary's key. I have written a script

Use sets. Sets are easier to use and much faster:

 d1 = {'a': 1, 'b': 2, 'c': 3}
 d2 = {'b': 2, 'c': 3, 'd': 4}
 d1.keys()
['a', 'c', 'b']
 d2.keys()
['c', 'b', 'd']

 s1 = set(d1)
 s2 = set(d2)
 s1
set(['a', 'c', 'b'])
 s2
set(['c', 'b', 'd'])

 s1.intersection(s2)
set(['c', 'b'])
 s1.union(s2)
set(['a', 'c', 'b', 'd'])
 s1.difference(s2)
set(['a'])

Christian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing Dictionaries

2007-07-31 Thread Alex Martelli
Kenneth Love [EMAIL PROTECTED] wrote:
   ...
 Python in a Nutshell (2nd ed.)
   ...
 I am a slow reader.  So, if Doctests are mentioned in any of the above,
 I haven't encountered it yet.

Yep, I cover doctest in the chapter on testing, debugging, profiling and
optimizing.


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: Re: Comparing Dictionaries

2007-07-30 Thread Kenneth Love

From: Steven D'Aprano [EMAIL PROTECTED]
Newsgroups: comp.lang.python
Subject: Re: Comparing Dictionaries
Date: Sat, 28 Jul 2007 10:21:14 +1000
To: python-list@python.org

On Fri, 27 Jul 2007 14:11:02 -0500, Kenneth Love wrote:

  The published recipe (based on ConfigParser) did not handle my INI
  files.  I have periods in both the section names and the key names.
  The INI files contents were developed according to an internally
  defined process that other non-Python programs rely on.  The published
  recipe *did not work* with this scenario.

I think you have made a mistake. ConfigParser as published certainly DOES
accept periods in section and option names. It just *works*.

The recipe I'm using is based upon ConfigParser and creates a dictionary
that is based on the contents of the INI file.  The dictionary's key is
based on the section name and the key name from the INI file.  The two
are concatenated with a separator.

In the original recipe, the separator is a period.  To use your example
(deleted as an attempt at brevity), the dictionary would be:

{ SECTION.FRED.option.wilma : 45 }

As originally written, the section name is now SECTION when you write
the INI file back out.  The key is FRED.option.wilma.

Here is the original recipe:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65334

My version replaces the period with a dollar sign giving:

{ SECTION.FRED$option.wilma : 45 }

I also removed the import string and put both the load() and save()
functions in a file with proper comments and the Python equivalent of
Javadoc comments.

Even if the existing ConfigParser doesn't do what you want, the right way
to fix the problem is not to recreate the entire module from scratch, but
to subclass it:
[snip]

In no way did I rewrite ConfigParser.  I have a real job with time
pressures and I'm not so arrogant as to think I could whip something
up in an hour that would be anywhere close to correct.

I see that I wasn't as clear as I thought I was in my original post
as you are second person to think I was developing my own INI solution.

All I wanted to know was How do I compare two dictionaries to see if
they are equal?.  It turns out that this functionality is built-in
and it is my own stupid fault that my unit test was failing (modifying
working code and writing a unit test at the same time is a recipe for
failure).

Oh well.  Next time I'll spend two hours trying to figure it out instead
of one before I post.  :-\

--
Steven.

--
http://mail.python.org/mailman/listinfo/python-list

-- 
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Kenneth Love   | Oklahoma Tax Commission
DP Programmer/Analyst  | Information Technology
(405) 522 - 5864   | http://www.tax.ok.gov/
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing Dictionaries

2007-07-30 Thread Kenneth Love
At 03:23 AM 7/28/2007, you wrote:
Hi Kenneth,  being new to Python i wondered if you at least considered
Doctests as part of your testing solution.
Other languages don't have Doctest.

- Paddy.

Until I read your post, I had never even heard of Doctest.  I will look
into it.

Here is the list of online sources I've found:

http://www.ibiblio.org/obp/thinkCSpy/index.html
http://www.diveintopython.org/toc/index.html
http://aspn.activestate.com/ASPN/Cookbook/Python


Here are the O'Reilly books I purchased from Barnes  Noble:

Python in a Nutshell (2nd ed.)
Python Cookbook (2nd ed.)
Programming Python (3rd ed.)

I am a slow reader.  So, if Doctests are mentioned in any of the above,
I haven't encountered it yet.

Specifically, my information on unit testing comes from reading about
half of this online chapter:

http://www.diveintopython.org/unit_testing/index.html

I will search on Google for more info on Doctest.

Thanks!

Sincerely,
Kenneth Love


-- 
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Kenneth Love   | Oklahoma Tax Commission
DP Programmer/Analyst  | Information Technology
(405) 522 - 5864   | http://www.tax.ok.gov/
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing Dictionaries

2007-07-30 Thread Paddy
On Jul 30, 8:30 pm, Kenneth Love [EMAIL PROTECTED] wrote:
 At 03:23 AM 7/28/2007, you wrote:

 Hi Kenneth,  being new to Python i wondered if you at least considered
 Doctests as part of your testing solution.
 Other languages don't have Doctest.

 - Paddy.

 Until I read your post, I had never even heard of Doctest.  I will look
 into it.

 Here is the list of online sources I've found:

 http://www.ibiblio.org/obp/thinkCSpy/index.htmlhttp://www.diveintopython.org/toc/index.htmlhttp://aspn.activestate.com/ASPN/Cookbook/Python

 Here are the O'Reilly books I purchased from Barnes  Noble:

 Python in a Nutshell (2nd ed.)
 Python Cookbook (2nd ed.)
 Programming Python (3rd ed.)

 I am a slow reader.  So, if Doctests are mentioned in any of the above,
 I haven't encountered it yet.

 Specifically, my information on unit testing comes from reading about
 half of this online chapter:

 http://www.diveintopython.org/unit_testing/index.html

 I will search on Google for more info on Doctest.

 Thanks!

 Sincerely,
 Kenneth Love

Add to your list:
  
http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-2-doctest.html
  http://en.wikipedia.org/wiki/Doctest

Have fun.

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing Dictionaries

2007-07-30 Thread Paul Rubin
Kenneth Love [EMAIL PROTECTED] writes:
 I will search on Google for more info on Doctest.

Doctest is recent.  Try:

http://python.org/doc/lib/module-doctest.html

Diveintopython should probably be updated to use doctest instead
of unittest.  unittest is Java-descended and doesn't fit into Python
as well as doctest does.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fwd: Re: Comparing Dictionaries

2007-07-30 Thread Steven D'Aprano
On Mon, 30 Jul 2007 14:06:29 -0500, Kenneth Love wrote:

 
From: Steven D'Aprano [EMAIL PROTECTED]
Newsgroups: comp.lang.python
Subject: Re: Comparing Dictionaries
Date: Sat, 28 Jul 2007 10:21:14 +1000
To: python-list@python.org

On Fri, 27 Jul 2007 14:11:02 -0500, Kenneth Love wrote:

  The published recipe (based on ConfigParser) did not handle my INI
  files.  I have periods in both the section names and the key names.
  The INI files contents were developed according to an internally
  defined process that other non-Python programs rely on.  The published
  recipe *did not work* with this scenario.

I think you have made a mistake. ConfigParser as published certainly DOES
accept periods in section and option names. It just *works*.
 
 The recipe I'm using is based upon ConfigParser and creates a dictionary
 that is based on the contents of the INI file.  The dictionary's key is
 based on the section name and the key name from the INI file.  The two
 are concatenated with a separator.
 
 In the original recipe, the separator is a period.  To use your example
 (deleted as an attempt at brevity), the dictionary would be:
 
 { SECTION.FRED.option.wilma : 45 }

Well, that's just broken.

Flat is better than nested is only true when things are actually better
flat rather than nested. The right way to build a dictionary from an INI
file is with nested dictionaries:

{SECTION1: {option1: 20, option2: 30}, 
SECTION2: {option1, 2.0, option2: 3.0}}

That treats each section as a single piece.

But if you absolutely insist on flattening the dictionary, the right way
is not to concatenate the section name and the option name into a single
string, but to use a tuple (SECTION, option).

[snip]

 In no way did I rewrite ConfigParser.  I have a real job with time
 pressures and I'm not so arrogant as to think I could whip something
 up in an hour that would be anywhere close to correct.
 
 I see that I wasn't as clear as I thought I was in my original post
 as you are second person to think I was developing my own INI solution.

Copying somebody else's code and modifying it is still recreating an
existing solution. Python has an INI file parser. What does it not do that
you have to recreate it by creating your own version?

Oh, ironically, the recipe you borrowed in fact uses the Python
ConfigParser to do all the heavy work. All it really does is flatten the
ConfigParser nested dictionary into a flat dictionary. I fail to see the
advantage.


 All I wanted to know was How do I compare two dictionaries to see if
 they are equal?.

Yes, but I suspect what you _wanted_ to know and what you _needed_ to know
are different.



-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing Dictionaries

2007-07-28 Thread Paddy
Hi Kenneth,  being new to Python i wondered if you at least considered
Doctests as part of your testing solution.
Other languages don't have Doctest.

- Paddy.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing Dictionaries

2007-07-28 Thread Martin P. Hellwig
Kenneth Love wrote:
cut
 That should teach me not to change working code at the same time I am
 writing unit tests.  Even so, I realize it won't be the last time I
 do something so silly.  Yes, I know about TDD's write the test first,
 but I'm not comfortable with the philosophy of these new fangled unit
 tests yet.
 
cut
I've been using python for about 3 years now, it was the first 
programming language I learned and I haven't done any other since (well 
that is if you dismiss sql and shell scripting on various platforms).

Though in my daily job I have some coding tasks, I do not see my self as 
a programmer since in my perspective a programmer is someone who can 
write good code regardless of the language. My code isn't any good, it 
is barely functional (so I really needed unit-test way of coding, for my 
own protection and not even because it gives more maintenance security 
for the project).

But the funny thing that I have seen in the development scene is that 
writing tests first and code later is a lot easier when you have a 
technical specification to base it on. A technical specification is of 
course based on a functional design. A functional design is written on 
the base of the assignment and the scope definition.

The scope and design can change in the course of the project but good 
practice is usually to do changes in another release. And that is what 
software change management and release management is for.

Still there are tons of reasons why you shouldn't follow blindly the 
best practice, since best practice is founded on theory molded around 
the most occurring reality. And the only thing that I am absolutely sure 
of is that reality differs enough from person to person and situation to 
situation, that forcing the same practice to every person/situation is a 
guarantee for wasting time and energy.

IMHO there are two extreme basic types of programmers, on the left are 
the ones that have a problem them self, solve it while happily hacking 
along the way, leaving the design part for a later stage, on the right 
are people that know beforehand on an almost bit level what a program is 
supposed to do, already have a design and aren't really that interested 
in the problem that their code should solve in the first place.

Me I am a bit schizophrenic, I move in between of them, on a hourly 
base. So for me the reality is that I have a certain 'problem' I write 
some code with the built-in IDLE mostly following functional coding 
practice (since I still have to figure out how some stuff works in 
python).

Then when I have a an idea what I am doing, I create a new project tree 
in subversion and write my technical specification (still having IDLE 
open to test some of the wild ideas that pop-up along the way).

After that I open Eclipse/PyDEV and start working on the unit-test and 
follow from there, when the code is finished I check it in and branch it 
as 0.0.1. Sleep over it and probably refactor it later on because I 
didn't like some variables names and want to add some comments in the 
code or move out some code to other classes, etc. etc.

The only problem is that I wish I was a bit more stable, because several 
times it has happend that I thought that the problem is a one-liner, so 
skipped the whole part after the figure-out-the-problem-code and used 
that what I have already written. Sometimes that works out well, but if 
it doesn't it always bites me hard.

But all these are just experiences from my side, I have no idea whether 
I am right or not, but for me it seems to work, so don't take it as 
advice (I am not really the person to take advice from) but as a little 
'story' along the way :-)

-- 
mph
-- 
http://mail.python.org/mailman/listinfo/python-list


Test-driven design (was: Comparing Dictionaries)

2007-07-28 Thread Ben Finney
Martin P. Hellwig [EMAIL PROTECTED] writes:

 But the funny thing that I have seen in the development scene is
 that writing tests first and code later is a lot easier when you
 have a technical specification to base it on. A technical
 specification is of course based on a functional design. A
 functional design is written on the base of the assignment and the
 scope definition.

This is, to my mind, one of the greatest advantages of test-driven
development: if you're not clear on how the code will be used, you
can't write the test, and (by the discipline of TDD) you can't write
the code either.

Therefore, you're forced to confront the fuzziness of your design
*before* it causes you to write meaningless code – but only to the
extent necessary to write the code at hand. If understanding the code
you're about to write requires some more extensive design thinking,
that's all to the good; but if you have enough understanding to write
a test for the small area you're on, you don't need to do a huge
amount of design. The stark confrontation of needing to write the unit
test up front shows you the difference, at exactly the time it's most
useful.

There are many who call TDD test-driven design for this same reason.

-- 
 \ A child of five could understand this. Fetch me a child of |
  `\   five.  -- Groucho Marx |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Comparing Dictionaries

2007-07-27 Thread Ali
On Jul 26, 10:18 pm, Kenneth Love [EMAIL PROTECTED] wrote:
 Hello,

 I am new to Python, but not programming.  I would like to start my
 Python career by developing programs according to the best practices
 of the industry.  Right now, that appears to be unit tests, patterns,
 and source code control.

I am not sure about best, but one of my favourite practices is to
not re-write code that other people have written, and have released
under licenses that allow you to do anything with it.

 So, I am trying to write a unit test for some code that reads a Windows
 style INI file and stores the section, key, and values in a dictionary

So, in the standard library: http://docs.python.org/lib/module-ConfigParser.html
And if you want a more involved approach: 
http://www.voidspace.org.uk/python/configobj.html

Ali

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing Dictionaries

2007-07-27 Thread Kenneth Love
At 09:55 PM 7/26/2007, Ben Finney wrote:
Kenneth Love [EMAIL PROTECTED] writes:

  In other words, I consider these two dictionaries to be equivalent:
 
  { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'mickey' }
  { 'mouse' : 'mickey', 'dog' : 'bone', 'cat' : 'fever' }
 
  while these two are not:
 
  { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'mickey' }
  { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'michael' }
 
  Any suggestions on how to compare these via some assert statement?

Dictionaries already know how to compare themselves to each other.

  {'dog': 'bone', 'cat': 'fever', 'mouse': 'mickey'} == {'mouse': 
 'mickey', 'dog': 'bone', 'cat': 'fever'}
 True
  {'dog': 'bone', 'cat': 'fever', 'mouse': 'mickey'} == {'mouse': 
 'michael', 'dog': 'bone', 'cat': 'fever'}
 False

After verifying this myself, I double checked my code.  It turns out,
the changes I made to get rid of the import string from the original
recipe were the problem.  Leaving the parenthesis off lower() and
strip() in the following code causes all sorts of problems:

 config[%s$%s % (name, key.lower())] = cp.get(sec, key).strip()

That should teach me not to change working code at the same time I am
writing unit tests.  Even so, I realize it won't be the last time I
do something so silly.  Yes, I know about TDD's write the test first,
but I'm not comfortable with the philosophy of these new fangled unit
tests yet.

Thanks for the help!

Sincerely,
Kenneth Love


-- 
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Kenneth Love   | Oklahoma Tax Commission
DP Programmer/Analyst  | Information Technology
(405) 522 - 5864   | http://www.tax.ok.gov/
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing Dictionaries

2007-07-27 Thread Kenneth Love
At 04:42 AM 7/27/2007, Ali wrote:
On Jul 26, 10:18 pm, Kenneth Love [EMAIL PROTECTED] wrote:
  Hello,
 
  I am new to Python, but not programming.  I would like to start my
  Python career by developing programs according to the best practices
  of the industry.  Right now, that appears to be unit tests, patterns,
  and source code control.

I am not sure about best, but one of my favourite practices is to
not re-write code that other people have written, and have released
under licenses that allow you to do anything with it.

  So, I am trying to write a unit test for some code that reads a Windows
  style INI file and stores the section, key, and values in a dictionary

So, in the standard library: 
http://docs.python.org/lib/module-ConfigParser.html
And if you want a more involved approach: 
http://www.voidspace.org.uk/python/configobj.html

Ali

The published recipe (based on ConfigParser) did not handle my INI
files.  I have periods in both the section names and the key names.
The INI files contents were developed according to an internally
defined process that other non-Python programs rely on.  The published
recipe *did not work* with this scenario.

Believe me, not modifying 3rd-party code is something I prefer and
already practice.  The code has to work first.

In case anyone is curious, here is a link to the original:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65334

I combined the load/save routines, slogged through the unfamiliar
syntax, changed the section/key separator to '$', and started
writing unit tests.

Sincerely,
Kenneth Love


-- 
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Kenneth Love   | Oklahoma Tax Commission
DP Programmer/Analyst  | Information Technology
(405) 522 - 5864   | http://www.tax.ok.gov/
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing Dictionaries

2007-07-27 Thread Steven D'Aprano
On Fri, 27 Jul 2007 14:11:02 -0500, Kenneth Love wrote:

 The published recipe (based on ConfigParser) did not handle my INI
 files.  I have periods in both the section names and the key names.
 The INI files contents were developed according to an internally
 defined process that other non-Python programs rely on.  The published
 recipe *did not work* with this scenario.

I think you have made a mistake. ConfigParser as published certainly DOES
accept periods in section and option names. It just *works*.

Here's my INI file:

[SECTION.FRED]
option.wilma = 45



And here's how I read it:

 import ConfigParser
 D = ConfigParser.ConfigParser()
 D.read('Desktop/data.ini')
['Desktop/data.ini']
 D.sections()
['SECTION.FRED']
 D.options('SECTION.FRED')
['option.wilma']
 D.getint('SECTION.FRED', 'option.wilma')
45


Even if the existing ConfigParser doesn't do what you want, the right way
to fix the problem is not to recreate the entire module from scratch, but
to subclass it:


import ConfigParser

class MyConfigParser(ConfigParser.ConfigParser):
# Warning: untested. I haven't even looked at the source code
# of the original.
def getint(self, section, option):
value = super(MyConfigParser, self).getint(section, option)
return value + 1


(Although, it has to be said... if somebody can subclass ConfigParser so
that writing a modified file doesn't remove comments, I'll be mightily
impressed.)


-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Comparing Dictionaries

2007-07-26 Thread Kenneth Love

Hello,

I am new to Python, but not programming.  I would like to start my
Python career by developing programs according to the best practices
of the industry.  Right now, that appears to be unit tests, patterns,
and source code control.

So, I am trying to write a unit test for some code that reads a Windows
style INI file and stores the section, key, and values in a dictionary
(recipe originally found on ASPN, but heavily modified for my needs).

--
class LoadIni(unittest.TestCase):
 knownDefault = {
 database$dbms:mysql,
 database$name:thelarch,
 database$user:nobody,
 database$password:special,
 database$host:127.0.0.1
 }

 def testNoIniFilename(self):
 A default configuration list should be returned.
 result = ini.load()
 # These next two print statement show the same key/value pairs,
 # but in a different order.
 #print knownDefault
 #print result
 self.assertEqual(result, self.knownDefault)  # does not work
---

In this case, I need to compare the returned dictionary (result) with
the known default dictionary (knownDefault).  This needs to be a
comparison of the dictionary key/value pairs.  If all of the key/value
pairs are an exact match and no extra key/value pairs are in either
dictionary then I consider the two dictionaries to be equivalent.

In other words, I consider these two dictionaries to be equivalent:

 { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'mickey' }
 { 'mouse' : 'mickey', 'dog' : 'bone', 'cat' : 'fever' }

while these two are not:

 { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'mickey' }
 { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'michael' }

Any suggestions on how to compare these via some assert statement?

Am I even on the right track with the INI file storing results in a
dictionary?  When I found the code, it just felt right.

NOTE: The code works, I can load the INI file, programmatically change
a few settings, save the results to a new INI file, and manually compare
the resulting files.  I get the expected results.  It is the automation
of this testing process that appears to be the stumbling block.

adTHANKSvance,
Kenneth Love


-- 
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Kenneth Love   | Oklahoma Tax Commission
DP Programmer/Analyst  | Information Technology
(405) 522 - 5864   | http://www.tax.ok.gov/
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing Dictionaries

2007-07-26 Thread Ben Finney
Kenneth Love [EMAIL PROTECTED] writes:

 In other words, I consider these two dictionaries to be equivalent:
 
 { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'mickey' }
 { 'mouse' : 'mickey', 'dog' : 'bone', 'cat' : 'fever' }
 
 while these two are not:
 
 { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'mickey' }
 { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'michael' }
 
 Any suggestions on how to compare these via some assert statement?

Dictionaries already know how to compare themselves to each other.

 {'dog': 'bone', 'cat': 'fever', 'mouse': 'mickey'} == {'mouse': 
'mickey', 'dog': 'bone', 'cat': 'fever'}
True
 {'dog': 'bone', 'cat': 'fever', 'mouse': 'mickey'} == {'mouse': 
'michael', 'dog': 'bone', 'cat': 'fever'}
False

-- 
 \ Many are stubborn in pursuit of the path they have chosen, few |
  `\  in pursuit of the goal.  -- Friedrich Nietzsche |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Comparing dictionaries, is this valid Python?

2005-12-13 Thread François Pinard
Hi, people.

I noticed today that dictionaries seem to support `==' comparison.  
(Retrospectively, it is strange that I never needed it before! :-)
Yet, before relying on this, I seeked for confirmation in the Python 
manuals, and did not succeed in finding it.  In particular:

   http://www.python.org/doc/2.3.5/lib/typesmapping.html

is silent on the subject.  As for:

   http://www.python.org/doc/2.3.5/lib/comparisons.html

it only says Comparison operations are supported by all objects, which 
is a little vague, and no promise that comparisons are meaningful (for 
example, one might wonder what would exactly mean the comparison of open 
files).  The node even says: Two more operations with the same 
syntactic priority, in and not in, are supported only by sequence 
types (below)., which suggests that the information might not be fully
up-to-date, at least regarding dictionaries.

Would someone know where I could find a confirmation that comparing 
dictionaries with `==' has the meaning one would expect (even this is 
debatable!), that is, same set of keys, and for each key, same values?

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing dictionaries, is this valid Python?

2005-12-13 Thread Tim Peters
[François Pinard]
...
 Would someone know where I could find a confirmation that comparing
 dictionaries with `==' has the meaning one would expect (even this is
 debatable!), that is, same set of keys, and for each key, same values?

Yes, look here wink:  it has the meaning you expect, provided that
by same you mean compare equal (and not, e.g, is).

See the Language Reference Manual, section 5.9 Comparisons, for
more, and footnote 5.5 there for a bit of history.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing dictionaries, is this valid Python?

2005-12-13 Thread Peter Hansen
François Pinard wrote:
 As for:
 
http://www.python.org/doc/2.3.5/lib/comparisons.html
 
 it only says Comparison operations are supported by all objects, which 
 is a little vague, and no promise that comparisons are meaningful (for 
 example, one might wonder what would exactly mean the comparison of open 
 files).  

I'm not checking the 2.3.5 version, but that latest one is fairly clear 
on what comparisons on mappings do:

http://docs.python.org/ref/comparisons.html

The same behaviour applied to 2.3.5 though, I believe, so maybe that's 
sufficient for you.

-Peter

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing dictionaries, is this valid Python?

2005-12-13 Thread François Pinard
[Peter Hansen]

 it only says Comparison operations are supported by all objects 
 [...]

I'm not checking the 2.3.5 version, but that latest one is fairly clear 
on what comparisons on mappings do:

http://docs.python.org/ref/comparisons.html

Yes, indeed.  Thanks a lot!

-- 
François Pinard   http://pinard.progiciels-bpi.ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing dictionaries, is this valid Python?

2005-12-13 Thread Mike Meyer
François Pinard [EMAIL PROTECTED] writes:
 Would someone know where I could find a confirmation that comparing
 dictionaries with `==' has the meaning one would expect (even this is
 debatable!), that is, same set of keys, and for each key, same values?

It may not exist, so you'll have to go look at the source. That sure
looks like it does what you expect.

However, you should know that *any* to objects in python can be
compared for equality. The default behavior is to check to see if they
are the same object. If some class or type does anything else, it'll
have code to do the comparison. You can check the latter behavior
yourself pretty easily:

 a = dict(a = 1)
 b = dict(a = 1)
 a is b
False
 a == b
True

So dictionaries have their own comparison code. I can't think of much
else it could be but what you suggest.

Now, what asking if one dictionary is less than another means, there
you're on your own (but that's in the source as well).

   mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list