python字典

  dic = {'姓名':'A','age':23,'地址':'hn'}
   print ( dic['age'])
字典存储内容是通过键值对存储的,取出是通过键取值
字典取值,使用中括号,通过键 取的值
  dic = [
    {'姓名':'A','age':23,'地址':'hen'},
   {'姓名':'b','age':24,'地址':'hdn'},
  {'姓名':'c','age':25,'地址':[1,2,3,4,]},
         ]
     print(dic[2]['地址'][2])
    for temp in dic :
       print(temp)

增加 字典键 = [值] 如果键值不存在 就增加新的键值对

    dic = {'name':'li','id':2}
    dic['age']=20
    print(dic)

改 字典键 = [值] 如果键值存在 就修改键值

   dic = {'name':'li','id':2}
   dic['id'] = 6
   print(dic)

删 字典.pop(键) 根据键删除指定的值 并返回值

   dic = {'name':'li','id':2}
   sid=dic.pop('id')
   print(dic)
   print(sid)

删 del 字典[键] 根据键删除指定的值

   dic ={'id':12,'name':'li','age':20}
   del dic['age']
   print(dic)

清空 字典.clear() 清空字典里的所有键值对

    dic ={'id':12,'name':'li','age':20}
    dic.clear()
    print(dic)

查 值 = 字典[键] 根据键查询值

  dic ={'id':12,'name':'li','age':20}
  val = dic['id']
  print(val)
  print ('*'*30)

查 字典.get(键 [,默认值]) 用Get方法通过键取值,值存在,返回值,不存在返回None,或默认值可修改

  dic ={'id':12,'name':'li','age':20}
  age = dic.get('age')
  score = dic.get('score','无成绩')
  print(age)
  print(score)

查 len(字典) 计算字典元素个数,即键值对总数

    dic ={'id':12,'name':'li','age':20}
    lenth = len(dic)
    print (lenth)

字典.keys() 返回所有的键

     dic ={'id':12,'name':'li','age':20}
     keys = dic.keys()
     for i in keys :
        print('%s %s'%(i,dic[i]))
        print(i)
      print(keys)

字典.keys() 返回所有的值

    dic ={'id':12,'name':'li','age':20}
   vals = dic.values()
    for i in vals :
       print(i)
    print(vals)

字典.items() 返回所有的键值对

  dic ={'id':12,'name':'li','age':20}
  items = dic.items()
  for i in items :
    print(i)
   print(items)


   dic ={'id':12,'name':'li','age':20}
   items = dic.items()
   for k,v in items :
       print('%s %s'%(k,v))

in 是否存在 只能查看键是否存在

  dic ={'id':12,'name':'li','age':20}
  print('id' in dic)

字典.copy() 返回一个新的字典

    dic ={'id':12,'name':'li','age':20}
    dic1 = dic.copy()
    print(dic1)

字典.fromkeys(seq[key,key1.],val) seq 序列 返回一个新的字典 val 为初始值

     dic ={'id':12,'name':'li','age':20}
     dic1=dic.fromkeys([1,2,3],'q')
     print (dic1)

字典.setdefault(key,default = None) 如果键key不在字典中,则向字典中添加key并使用默认值,若存在字典中则返回字典中的值

     dic ={'id':12,'name':'li','age':20}
     val=dic.setdefault('id')
     print (dic)
     print(val)
     print(dic.setdefault('score',110))
     print(dic)

字典1.update(字典2) 把字典2中的键值对更新到字典1中,不影响字典1

 dic ={'id':12,'name':'li','age':20}
 dic1 = {'score':110}
 dic.update(dic1)
 print(dic)
 print(dic1)

你可能感兴趣的:(python字典)