Accessing elements of Python dictionary by index

后端 未结 10 1688
说谎
说谎 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

    Given that it is a dictionary you access it by using the keys. Getting the dictionary stored under "Apple", do the following:

    >>> mydict["Apple"]
    {'American': '16', 'Mexican': 10, 'Chinese': 5}
    

    And getting how many of them are American (16), do like this:

    >>> mydict["Apple"]["American"]
    '16'
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 09:13

    Simple Example to understand how to access elements in the dictionary:-

    Create a Dictionary

    d = {'dog' : 'bark', 'cat' : 'meow' } 
    print(d.get('cat'))
    print(d.get('lion'))
    print(d.get('lion', 'Not in the dictionary'))
    print(d.get('lion', 'NA'))
    print(d.get('dog', 'NA'))
    

    Explore more about Python Dictionaries and learn interactively here...

    0 讨论(0)
  • 2020-11-22 09:15

    You can use dict['Apple'].keys()[0] to get the first key in the Apple dictionary, but there's no guarantee that it will be American. The order of keys in a dictionary can change depending on the contents of the dictionary and the order the keys were added.

    0 讨论(0)
  • 2020-11-22 09:17

    As a bonus, I'd like to offer kind of a different solution to your issue. You seem to be dealing with nested dictionaries, which is usually tedious, especially when you have to check for existence of an inner key.

    There are some interesting libraries regarding this on pypi, here is a quick search for you.

    In your specific case, dict_digger seems suited.

    >>> import dict_digger
    >>> d = {
      'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
      'Grapes':{'Arabian':'25','Indian':'20'} 
    }
    
    >>> print(dict_digger.dig(d, 'Apple','American'))
    16
    >>> print(dict_digger.dig(d, 'Grapes','American'))
    None
    
    0 讨论(0)
  • 2020-11-22 09:22

    Few people appear, despite the many answers to this question, to have pointed out that dictionaries are un-ordered mappings, and so (until the blessing of insertion order with Python 3.7) the idea of the "first" entry in a dictionary literally made no sense. And even an OrderedDict can only be accessed by numerical index using such uglinesses as mydict[mydict.keys()[0]] (Python 2 only, since in Python 3 keys() is a non-subscriptable iterator.)

    From 3.7 onwards and in practice in 3,6 as well - the new behaviour was introduced then, but not included as part of the language specification until 3.7 - iteration over the keys, values or items of a dict (and, I believe, a set also) will yield the least-recently inserted objects first. There is still no simple way to access them by numerical index of insertion.

    As to the question of selecting and "formatting" items, if you know the key you want to retrieve in the dictionary you would normally use the key as a subscript to retrieve it (my_var = mydict['Apple']).

    If you really do want to be able to index the items by entry number (ignoring the fact that a particular entry's number will change as insertions are made) then the appropriate structure would probably be a list of two-element tuples. Instead of

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

    you might use:

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

    Under this regime the first entry is mylist[0] in classic list-endexed form, and its value is ('Apple', {'American':'16', 'Mexican':10, 'Chinese':5}). You could iterate over the whole list as follows:

    for (key, value) in mylist:  # unpacks to avoid tuple indexing
        if key == 'Apple':
            if 'American' in value:
                print(value['American'])
    

    but if you know you are looking for the key "Apple", why wouldn't you just use a dict instead?

    You could introduce an additional level of indirection by cacheing the list of keys, but the complexities of keeping two data structures in synchronisation would inevitably add to the complexity of your code.

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