Accessing elements of Python dictionary by index

后端 未结 10 1699
说谎
说谎 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: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])
    

提交回复
热议问题