enumerate() for dictionary in python

前端 未结 11 1191
走了就别回头了
走了就别回头了 2020-12-08 05:55

I know we use enumerate for iterating a list but I tried it in a dictionary and it didn\'t give an error.

CODE:

enumm = {0: 1, 1: 2, 2:          


        
相关标签:
11条回答
  • 2020-12-08 06:28
    d = {0: 'zero', '0': 'ZERO', 1: 'one', '1': 'ONE'}
    
    print("List of enumerated d= ", list(enumerate(d.items())))
    

    output:

    List of enumerated d=  [(0, (0, 'zero')), (1, ('0', 'ZERO')), (2, (1, 'one')), (3, ('1', 'ONE'))]
    
    0 讨论(0)
  • 2020-12-08 06:31

    Just thought I'd add, if you'd like to enumerate over the index, key, and values of a dictionary, your for loop should look like this:

    for index, (key, value) in enumerate(your_dict.items()):
        print(index, key, value)
    
    0 讨论(0)
  • 2020-12-08 06:45

    You may find it useful to include index inside key:

    d = {'a': 1, 'b': 2}
    d = {(i, k): v for i, (k, v) in enumerate(d.items())}
    

    Output:

    {(0, 'a'): True, (1, 'b'): False}
    
    0 讨论(0)
  • 2020-12-08 06:49
    dict1={'a':1, 'b':'banana'}
    

    To list the dictionary in Python 2.x:

    for k,v in dict1.iteritems():
            print k,v 
    

    In Python 3.x use:

    for k,v in dict1.items():
            print(k,v)
    # a 1
    # b banana
    

    Finally, as others have indicated, if you want a running index, you can have that too:

    for i  in enumerate(dict1.items()):
       print(i)  
    
     # (0, ('a', 1))
     # (1, ('b', 'banana'))
    

    But this defeats the purpose of a dictionary (map, associative array) , which is an efficient data structure for telephone-book-style look-up. Dictionary ordering could be incidental to the implementation and should not be relied upon. If you need the order, use OrderedDict instead.

    0 讨论(0)
  • 2020-12-08 06:49

    That sure must seem confusing. So this is what is going on. The first value of enumerate (in this case i) returns the next index value starting at 0 so 0, 1, 2, 3, ... It will always return these numbers regardless of what is in the dictionary. The second value of enumerate (in this case j) is returning the values in your dictionary/enumm (we call it a dictionary in Python). What you really want to do is what roadrunner66 responded with.

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