Accessing elements of Python dictionary by index

后端 未结 10 1804
说谎
说谎 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:28

    I know this is 8 years old, but no one seems to have actually read and answered the question.

    You can call .values() on a dict to get a list of the inner dicts and thus access them by index.

    >>> mydict = {
    ...  'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
    ...  'Grapes':{'Arabian':'25','Indian':'20'} }
    
    >>>mylist = list(mydict.values())
    >>>mylist[0]
    {'American':'16', 'Mexican':10, 'Chinese':5},
    >>>mylist[1]
    {'Arabian':'25','Indian':'20'}
    
    >>>myInnerList1 = list(mylist[0].values())
    >>>myInnerList1
    ['16', 10, 5]
    >>>myInnerList2 = list(mylist[1].values())
    >>>myInnerList2
    ['25', '20']
    

提交回复
热议问题