Dictionary of Dicts question

John Townsend jtownsen at adobe.com
Thu Oct 16 17:05:16 EDT 2008


Joe had a good point! Let me describe what problem I'm trying to solve and the list can recommend some suggestions.

I have two text files. Each file contains data like this:

Test file 1234 4567 8975

I want to compare the numbers in each text file. The data set (i.e. the numbers) has a unique identifier: the "test" + the "file". The text files are similar, but may not be exactly the same.

My initial idea was to read the text files and turn each line into a dictionary entry. A dict for each text file. Then walk through the dicts and compare the numbers.

If anyone has a better idea, I'd love to hear it.





-----Original Message-----
From: Joe Strout [mailto:joe at strout.net]
Sent: Thursday, October 16, 2008 1:49 PM
To: John Townsend
Subject: Re: Dictionary of Dicts question

On Oct 16, 2008, at 1:19 PM, John Townsend wrote:

> Accessing values is pretty straightforward (nice change from my Perl
> days). For example:
>
> myDict['TestName']['FileName']['ct_shutdown']
>
> in Python interpreter yields
>
> 9021

FWIW, I'd recommend you scrap this dict-of-dicts structure and instead
define a class (or three).  You'll know you have it right when instead
of the above, you're typing something like:

  myDict['TestName'].FileName.ct_shutdown

(The division might be a little different -- it's not entirely clear
to me what in your sample code is just place-holder names, and what is
meant literally.)

>  However, when I try to add, let's say, a new FileName entry, I end
> up replacing the previous FileName entry.
>
> In Python interpreter, I try:
>
> myDict['TestName'] = {'NewFileName': {}, }

Well, yes, this code says "stuff the new dictionary {'NewFileName':{}}
into myDict under 'TestName', replacing whatever was under 'TestName'
before."

If that's not what you want, then don't do that -- assign to
myDict['TestName2'] or some such.

> So, how do I add a new entry without replacing the old entry?

You don't; that's the whole point of dictionaries.  A dictionary maps
keys to values.  You can't have two values for the same key.  You
could have a key map to a list, but I suspect we're straying a bit far
now from whatever it is you're trying to accomplish.

If you can explain what it is you're actually trying to accomplish
(without reference to implementation details like dictionaries and
entries), maybe we can suggest a suitable approach.

Best,
- Joe




More information about the Python-list mailing list