Python07,字典

2021-06-17 13:03

阅读:553

标签:heap   嵌套   数据   返回   not   nan   foo   one   real   

字典是一种非常有用的数据类型,就像我们上学用到的字典,通过笔画和拼音来查找对应汉字的详细解释。

info = {    

   ‘stu101‘:"James",    

   ‘stu102‘:"Alex",    

   ‘stu103‘:"Paul",    

   ‘stu104‘:"Mark"

}

  • 字典是无序的
  • 字典的key必须是唯一的,没有重复项

字典的添加

  info[‘stu105‘] = "Lucy"

  print(info)

字典的删除

  info.pop(‘stu101‘)

  print(info)

还可以这样删除

  del info[‘stu102‘]

  print(info)

还可以随机删除

  info.popitem()

  print(info)

字典的修改,修改不存在的key会直接变成增加

  info[‘stu105‘] = "James"

  print(info)

字典的查找

  print(‘stu102‘ in info)  #判断key是否在字典中存在

  print(info.get(‘stu102‘))  #获取某个key对应的值,不存在则返回None

字典的多级嵌套

  food_catalog = {    

    ‘vegetables‘:{        

      "cabbage":[1.5,‘cheap‘],        

      "radish":[2.0,‘cheap‘],        

      "carrot":[2.5,‘cheap‘],    

  },    

    ‘fruit‘:{        

      "apple":[5.8,‘cheap‘],        

      "banana":[4.5,‘cheap‘],        

      "pear":[3.9,‘cheap‘],    

  },    

    ‘meats‘:{        

      "pork":[16,‘expensive‘],        

      "mutton":[28,‘expensive‘],        

      "beef":[48,‘expensive‘],    

  },    

    ‘drinks‘:{        

      "yogourt":[8,‘expensive‘],        

      "tea":[5,‘cheap‘],        

      "cola":[4,‘cheap‘],    

      }

  }

  food_catalog[‘drinks‘]["yogourt"][1] += ‘,not really‘

  print(food_catalog[‘drinks‘]["yogourt"])

Python07,字典

标签:heap   嵌套   数据   返回   not   nan   foo   one   real   

原文地址:https://www.cnblogs.com/wangfei1248/p/9721022.html


评论


亲,登录后才可以留言!