Python Forum
double keyed dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
double keyed dictionaries
#1
in many cases i need to go both ways in references held by a dictionary. i very often use the same one dictionary when i know the keys each way will not collide. for example my current project involves a file inode and that file's content digest. the digest is always a list of bytes and the inode is always an int. so i can just do the lookup with either and i'll get what i need. the value for inode is actually a list of inodes.

what i am looking around for is a simple way to iterate over one particular type of key and exclude the other. of course i can just test the key types:
# iterate digests
    for k in bigdict.keys():
        if isinstance(k,int):
            continue
        ...
but i would like some simpler way to structure this.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
You could just have two dicts and use a ChainMap for lookup
from collections import ChainMap

inodict = {}
digdict = {}
lookup = ChainMap(inodict, digdict)

if __name__ == '__main__':
    value = (23, 377, 922)
    inodict[12] = value
    digdict[b'abcde'] = value
    value = value + value
    inodict[42] = value
    digdict[b'eggs'] = value

    print(lookup[12])
    print(lookup[b'abcde'])
Why do you always manipulate inhomogeneous data? It makes code harder to write and to read. Refactoring literature advises against this.
Reply
#3
in a case like this, it does not make the code harder, at least the way i am accustomed to coding. i guess you could argue that these final scans are harder because of the need to distinguish cases. this is a fuzzy border case and i usually do have better success with the double dictionary. that and i am often testing key types for other reasons. i will go ahead and refactor this project and see how it makes things work for me. eventually it will be FOSS either way.

i started programming way back when i learned assembly language on IBM 360. i learned assembly on a dozen or so architectures since then and have used over a dozen higher level languages (C++, Java and Perl not among them). maybe my programming style is crazy. i'll need to see other ways succeed, to change. in the mean time, my way succeeds, though maybe only for me.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020