Accessing elements of Python dictionary by index

后端 未结 10 1698
说谎
说谎 2020-11-22 08:52

Consider a dict like

mydict = {
  \'Apple\': {\'American\':\'16\', \'Mexican\':10, \'Chinese\':5},
  \'Grapes\':{\'Arabian\':\'25\',\'Indian\':\'20\'} }
         


        
10条回答
  •  无人及你
    2020-11-22 09:09

    If the questions is, if I know that I have a dict of dicts that contains 'Apple' as a fruit and 'American' as a type of apple, I would use:

    myDict = {'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
              'Grapes':{'Arabian':'25','Indian':'20'} }
    
    
    print myDict['Apple']['American']
    

    as others suggested. If instead the questions is, you don't know whether 'Apple' as a fruit and 'American' as a type of 'Apple' exist when you read an arbitrary file into your dict of dict data structure, you could do something like:

    print [ftype['American'] for f,ftype in myDict.iteritems() if f == 'Apple' and 'American' in ftype]
    

    or better yet so you don't unnecessarily iterate over the entire dict of dicts if you know that only Apple has the type American:

    if 'Apple' in myDict:
        if 'American' in myDict['Apple']:
            print myDict['Apple']['American']
    

    In all of these cases it doesn't matter what order the dictionaries actually store the entries. If you are really concerned about the order, then you might consider using an OrderedDict:

    http://docs.python.org/dev/library/collections.html#collections.OrderedDict

提交回复
热议问题