Multilevel dicts/arrays v. tuples as keys? [Was: Re: Get keys from a dicionary]

Tim Golden mail at timgolden.me.uk
Mon Nov 14 05:42:50 EST 2011


On 14/11/2011 10:05, Matej Cepl wrote:
> Dne 11.11.2011 14:31, macm napsal(a):
>> def Dicty( dict[k1][k2] ):
>
> When looking at this I returned to the question which currently rolls in
> my mind:
>
> What's difference/advantage-disadvantage betweeng doing multi-level
> dicts/arrays like this and using tuple as a key? I.e., is it more
> Pythonic to have
>
> dict[k1,k2]
>
> instead?

For me, it would depend on what the data meant. To give an obvious 
example: if you were storing things which were based on coords, then 
clearly map[x, y] is more meaningful than map[x][y]. Conversely, if your 
dictionary structure was, say, a set of preferences for users, then 
prefs[username][prefname] is probably a more useful model.

Sometimes it's not so clear, in which case one person might opt for one 
approach while another opted for another while modelling the same data 
concepts. If, for example, you were modelling a set of book reviews 
where each review might have one or more genres (which you could display 
as a tag-cloud, say) then you could consider the model to be
a sort of book-genre tag cloud:

book_genres[title, genre]

or a list of books in each genre:

genres[genre][title]

or a list of genres for each book:

books[title][genre]

or even multiple ways if that made it easier to use in one situation
or another.

Stating-the-obvious-ly yours,

TJG



More information about the Python-list mailing list