美文网首页
python中的dict

python中的dict

作者: AngueTone | 来源:发表于2016-12-30 14:01 被阅读0次

    字典的添加、删除、修改操作

    dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
    dict["w"] = "watermelon"                              #添加
    del(dict["a"])                                                 #删除
    dict["g"] = "grapefruit"
    print dict.pop("b")    
    print dictdict.clear()                                      #清空
    print dict                                                                
    

    字典的遍历

            dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
             for k in dict:    
                      print "dict[%s] =" % k,dict[k]
    

    字典items()的使用

    dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
    

    每个元素是一个key和value组成的元组,以列表的方式输出print dict.items()

    调用items()实现字典的遍历

              dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
              for (k, v) in dict.items():    
                      print "dict[%s] =" % k, v
    

    调用iteritems()实现字典的遍历

            dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
              print dict.iteritems()
              for k, v in dict.iteritems():    
                      print "dict[%s] =" % k, v
              for (k, v) in zip(dict.iterkeys(), dict.itervalues()):    
                      print "dict[%s] =" % k, v
    

    每个元素是一个key和value组成的元组,以列表的方式输出
    print dict.items()
    dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
    it = dict.iteritems()
    print it

    遍历字典里面的内容

      dict = {'name':'python','english':33,'math':35}
      print dict.items()
      for i, j in dict.items():
       print 'dict[%s]=' % i, j
      #结果
      [('name', 'python'), ('math', 35), ('english', 33)]
      dict[name]= python
      dict[math]= 35
      dict[english]= 33
    

    或者:

      dict = {'name':'python','english':33,'math':35}
      for i in dict:
       print 'dict[%s]=' % dict[i]
      结果:
      dict[name]= python
      dict[math]= 35
      dict[english]= 33
    
    -------------------------------------------
    success_rate = {1:'1000000',2:'200000',3:'30000'}
    for k in success_rate:
        print success_rate[k]
        print k
    结果:
    1000000  
    1
    200000
    2
    30000
    3
    

    或者:

       for k,v in dict.iteritems():
       print 'dict[%s]' % k, v
        结果:
        dict[name] python
        dict[math] 35
        dict[english] 33

    相关文章

      网友评论

          本文标题:python中的dict

          本文链接:https://www.haomeiwen.com/subject/ggimmttx.html