The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

import-bot (20211) [Avatar] Offline
#1
[Originally posted by iri]

Hello,
I want to compare the keys of two dictionaries. How can I do that?
I've found that with dictionary.keys() I can obtain them and redirecting
the standard output to a file I could treat that file afterwards... But, is
there any way of doing it key by key and directly? I mean, from dictionary1 I
take the first key and search it in dictionary2 and so on...
Thank you very much!!

Irantzu
import-bot (20211) [Avatar] Offline
#2
Re: Comparing dictionaries
[Originally posted by hans]

Irantzu,

Are you looking for a merge? Please upgrade to Python2.2. Try

def merge(self,other)
for key in other:
if key not in self:
self[key] = other[key]


Regards, Hans

> Hello,
> I want to compare the keys of two dictionaries. How can I do that?
> I've found that with dictionary.keys() I can obtain them and redirecting
> the standard output to a file I could treat that file afterwards... But, is
> there any way of doing it key by key and directly? I mean, from dictionary1 I
> take the first key and search it in dictionary2 and so on...
> Thank you very much!!
>
> Irantzu
import-bot (20211) [Avatar] Offline
#3
Re: Comparing dictionaries
[Originally posted by d. harms]

Hi Irantzu,

You can compare the lists of keys for the two dictionaries.
The following example shows one way of doing this. The variables 'onlyIn1' and
'onlyIn2' are initialized with all the keys in in the first and second
dictionaries respectively.
Then the keys in the first dictionary are walked through and any key in both
dictionaries is removed from both lists.
So, at the end what remains in these variables are keys unique to the
respective dictionary.

>>> d1 = {'a': 1, 'b':2}
>>> d2 = {'b':1, 'c':2, 'd':3}
>>> onlyIn1 = d1.keys()
>>> onlyIn2 = d2.keys()
>>> inBoth = []
>>> for key in d1.keys():
if key in onlyIn2:
onlyIn2.remove(key)
onlyIn1.remove(key)
inBoth.append(key)


>>> onlyIn1
['a']
>>> onlyIn2
['c', 'd']
>>> inBoth
['b']
>>>


Hope this give you some ideas.

Cheers,

Daryl