简体   繁体   中英

Can anyone explain to me what a two-level dictionary is in Python

I am struggling to find any documentation anywhere on what this actually is. I understand just an ordinary dictionary. This consists of key and value pairs so if you search for a key its corresponding value is returned, For example:

myDict = {‘dog’ : ’fido’, ‘cat’ : ’tiddles’, ‘fish’ : ’bubbles’, ’rabbit’ : ’thumper’}

And then you can invoke certain methods on this like:

myDict[‘fish’]

returns

'bubbles'

or

myDict.has_key(‘tiddles’)

returns

True

How would a two-level dictionary compare to this?

It appears nested dictionaries was what I was looking for.

One more question, say I have a nested dictionary which links words to text files where the first integer is the number of the text file and the second is the number of occurrences:

myDict = {'through':{1:18,2:27,3:2,4:15,5:63}, 'one':{1:27,2:15,3:24,4:9,5:32}, 'clock':{1:2,2:5,3:9,4:6,5:15}

How would I use the file numbers to work out the total number of text files that were present? ie is there a way of extracting the number of key / value pairs in the inner dictionary?

I guess a two level dictionary could be a dictionary of dictionaries ie

dict = {'a':{"cool":1,"dict":2}}

you could use it like

dict['a']['cool'] 
>> 1

so you can do

dict['a'].has_key('cool')
>> True

It is just a nested dictionary, meaning it contains other dictionaries, for example

d = {'mike':{'age':10, 'gender':'male'}, 'jen':{'age':12, 'gender':'female'}}

I can access inner values such as

>>> d['mike']['age']
10

Common examples of deeply nested dictionaries in Python are reading and writing of JSON .

I believe you mean a two-way dictionary, here's a recipe (from Two way/reverse map ):

class TwoWayDict(dict):
    def __setitem__(self, key, value):
        # Remove any previous connections with these values
        if key in self:
            del self[key]
        if value in self:
            del self[value]
        dict.__setitem__(self, key, value)
        dict.__setitem__(self, value, key)

    def __delitem__(self, key):
        dict.__delitem__(self, self[key])
        dict.__delitem__(self, key)

    def __len__(self):
        """Returns the number of connections"""
        return dict.__len__(self) // 2

usage:

myDict = {‘dog’ : ’fido’, ‘cat’ : ’tiddles’, ‘fish’ : ’bubbles’, ’rabbit’ : ’thumper’}

twowaydict = TwoWayDict() # can't instantiate with old dict, need to setitem
for key in myDict: 
    twowaydict[key] = myDict[key]

twowaydict.has_key('tiddles')

returns True

If you mean a dict of dicts, that's fairly common construct, where the values of the containing dict are also dicts.

dofd = {'key1': {'subkey1': 'value1,1', 'subkey2': 'value1,2'}
        'key2': {'subkey1': 'value2,1', 'subkey2': 'value2,2'}
       }

and you'd access the internal values like this:

dofd['key1']['subkey2']

should return value1,2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM