开发小学生

导航

字典常用方法(增删改查)

1.创建字典

  1)dic = {}

  2)dic = {‘鱼类’:‘龙鱼’,‘鸟类’:‘鹰’}

  3)dic = dict(鱼类 =‘龙鱼’,鸟类 = ‘鹰’)

  4)dic = {x:x**2 for x in (2,4,6)}

  5)dic = dict.fromkeys([2,4,6,8],'好')

2.增加字典中的对象:

  1)dic['昆虫'] = '蝴蝶'

  2)dic.update({56:'jian','k4':'卡车'}) ---------------更新:key值存在更新至字典,key值不存在则添加至字典

  3)dic.copy(dic2)------------------------复制:将字典中对象复制到新字典中

3.删除字典中的对象:

  1)dic.pop("kk")-------------------'kk'为字典的key值

  2)del dic ----------------------------删除字典,字典无法继续被使用

  3)dic.clear()-------------------清空字典,字典可以继续被使用

4.更改字典中的对象:

  1)content['name'] = 'lll' --------------------------------直接对字符串内容赋值

  2)content['woniu'][0] = '33333' -------------------------列表赋值

  3)content['pc']['age'] = 20  ---------------------------字典赋值

  4)dic.update({56:'jian','k4':'卡车'}) ---------------更新:key值存在更新至字典,key值不存在则添加至字典

5.查询字典中的对象:

   1)len(conent)-------------------------查询字典长度

  2)content.keys()

  3)content.values()

  4)content.items()

  5)content[‘鱼类’]

  6)content.get("ndjandjs",'name')     如果ndjandjs不存在则使用name    返回值为true 和false

  7)content.has_key("name")

posted on 2020-05-12 11:56  开发小学生  阅读(222)  评论(0)    收藏  举报