代码之家  ›  专栏  ›  技术社区  ›  Georg Fritzsche

迭代defaultdict字典的键和值

  •  29
  • Georg Fritzsche  · 技术社区  · 14 年前

    d = [(1,2), (3,4)]
    for k,v in d:
      print "%s - %s" % (str(k), str(v))
    

    但这失败了:

    d = collections.defaultdict(int)
    d[1] = 2
    d[3] = 4
    for k,v in d:
      print "%s - %s" % (str(k), str(v))
    

    使用:

    Traceback (most recent call last):  
     File "<stdin>", line 1, in <module>  
    TypeError: 'int' object is not iterable 
    

    3 回复  |  直到 14 年前
        1
  •  86
  •   Deepstop    5 年前

    你需要反复研究 dict.iteritems()

    for k,v in d.iteritems():               # will become d.items() in py3k
      print "%s - %s" % (str(k), str(v))
    

    更新:在py3 V3.6中+

    for k,v in d.items():
      print (f"{k} - {v}")
    
        2
  •  23
  •   Vlad Bezden    7 年前

    如果您使用的是Python3.6

    from collections import defaultdict
    
    for k, v in d.items():
        print(f'{k} - {v}')
    
        3
  •  2
  •   Nguai al    6 年前

    from collections import defaultdict
    
    for k, values in d.items():
        for value in values:
           print(f'{k} - {value}')