Iterate over a dictionary in Python

This question already has an answer here:

  • Iterating over dictionaries using 'for' loops 12 answers

  • You iterate through a dictionary just like an array, but instead of giving you the values in the dictionary it gives you the keys.

    > my_dict = {"a" : 4, "b" : 7, "c" : 8}
    > for i in my_dict:
    ...  print i
    
    a
    b
    c
    

    You can then access the data in the dictionary like you normally would. (This is achieved with square brackets, so my_dict["a"] would give 4.)


    Dictionary has the ability to iterate over itself to print each item. To simply print the details of each item as you have asked, simply use the print command:

    >>> ourNewDict = {'name': 'Kyle', 'rank': 'n00b', 'hobby': 'computing'}
    >>> print ourNewDict
    
    Output: {'hobby': 'computing', 'name': 'Kyle', 'rank': 'n00b'}
    

    Or, to print keys and values independently:

    >>> print ourNewDict.keys()
    Output: ['hobby', 'name', 'rank']
    >>> print ourNewDict.values()
    Output: ['computing', 'Kyle', 'n00b']
    

    If I read into your question more, and guess that you'd like to iterate through each object to do more than simply print, then the items() command is what you need.

    >>> for key, value in ourNewDict.items():
    ...     print key
    ... 
    hobby
    name
    rank
    >>> for key, value in ourNewDict.items():
    ...     print value
    ... 
    computing
    Kyle
    n00b
    >>> 
    

    And to be very generic:

    >>>for someVariableNameHere in someDictionaryNameHere.items():
    ...     doStuff
    
    链接地址: http://www.djcxy.com/p/30364.html

    上一篇: 遍历每个键,它是一个函数的值

    下一篇: 在Python中迭代字典