Accessing elements of Python dictionary by index

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

    With the following small function, digging into a tree-shaped dictionary becomes quite easy:

    def dig(tree, path):
        for key in path.split("."):
            if isinstance(tree, dict) and tree.get(key):
                tree = tree[key]
            else:
                return None
        return tree
    

    Now, dig(mydict, "Apple.Mexican") returns 10, while dig(mydict, "Grape") yields the subtree {'Arabian':'25','Indian':'20'}. If a key is not contained in the dictionary, dig returns None.

    Note that you can easily change (or even parameterize) the separator char from '.' to '/', '|' etc.

    0 讨论(0)
  • 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']
    
    0 讨论(0)
  • 2020-11-22 09:29

    As I noticed your description, you just know that your parser will give you a dictionary that its values are dictionary too like this:

    sampleDict = {
                  "key1": {"key10": "value10", "key11": "value11"},
                  "key2": {"key20": "value20", "key21": "value21"}
                  }
    

    So you have to iterate over your parent dictionary. If you want to print out or access all first dictionary keys in sampleDict.values() list, you may use something like this:

    for key, value in sampleDict.items():
        print value.keys()[0]
    

    If you want to just access first key of the first item in sampleDict.values(), this may be useful:

    print sampleDict.values()[0].keys()[0]
    

    If you use the example you gave in the question, I mean:

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

    The output for the first code is:

    American
    Indian
    

    And the output for the second code is:

    American
    

    EDIT 1:

    Above code examples does not work for version 3 and above of python; since from version 3, python changed the type of output of methods keys and values from list to dict_values. Type dict_values is not accepting indexing, but it is iterable. So you need to change above codes as below:

    First One:

    for key, value in sampleDict.items():
        print(list(value.keys())[0])
    

    Second One:

    print(list(list(sampleDict.values())[0].keys())[0])
    
    0 讨论(0)
  • 2020-11-22 09:30

    You can't rely on order on dictionaries. But you may try this:

    dict['Apple'].items()[0][0]
    

    If you want the order to be preserved you may want to use this: http://www.python.org/dev/peps/pep-0372/#ordered-dict-api

    0 讨论(0)
提交回复
热议问题