一以贯之

python:数据类型dict

一、字典

key -->value 储存大量数据,而且是关系型数据,查询速度非常快

  数据类型分类:

    可变数据类型:list , dict, set

    不可变的数据类型:int , bool, str, tuple

    字典的键:不可变数据类型

    字典的值:任意数据类型

 

   hash哈希

    可变数据类型(不可哈希):list , dict,set

    不可变数据类型(可哈希):int , bool, str ,tuple

  增

    第一种 有则覆盖,没有就添加

dic = {"name":"jin",
       "age":18,
       "sex":"male"
       }
dic['hobby'] = 'girl'
print(dic)
dic['name'] = 'alex'
print(dic)
dic['hobby'] = 'love'
print(dic)

    第二种 setdefault,无则添加,有则不变

dic = {"name":"jin",
       "age":18,
       "sex":"male"
       }
dic.setdefault('work')
print(dic)
dic.setdefault('work','ps')
print(dic)
dic.setdefault('name')
print(dic)

  删

  

  pop有返回值(可以自己设置返回值) 

dic = {"name":"jin",
       "age":18,
       "sex":"male"
       }
print(dic.pop('age'))
print(dic.pop('name'))
 print(dic.pop('hahah','None'))
print(dic.pop('name','没有此关键值'))#添加返回值为‘没有此关键字’
没有设置返回值,并且也没有该元素,  会报错 

   clear清空

dic = {"name":"jin",
       "age":18,
       "sex":"male"
       }
 dic.clear()
 print(dic)

   del删除

dic = {"name":"jin",
       "age":18,
       "sex":"male"
       }

del dic
del dic['name']
print(dic)
del dic['work']
print(dic)
print(dic.popitem())#随机删除一对key--》value
print(dic)

  查

 

dic = {"name":"jin",
       "age":18,
       "sex":"male"
       }

print(dic['name'])
print(dic['work'])#没有,报错
print(dic['age'])
#print(dic('hobby1'))

print(dic.get('name'))
print(dic.get('name1','没有此贱'))#默认返回none,可以自己设置返回值
print(dic.get('name1'))

  其他方法 key()    values()  items()

print(dic.keys())
print(dic.keys(),type(dic.keys()))
for i in dic.keys():#打印键
   print(i)


for i in dic:#打印键
   print(i)

  

print(dic.values())
print(dic.values(),type(dic.values))

for i in dic.values():#将键值转化成列表,然后逐个打印
    print(i)

  

 

print(dic.items())


for i in dic.items():#将键和值转化成列表中成对的元祖
       print(i)
for k,v in dic.items():
print (k,v)

  分别赋值

 

 1 a, b = 2,3
 2 print(a,b)
 3 
 4 a,b = (2,3)
 5 print (a,b)
 6 
 7 a,b = [2,3]
 8  print (a,b)
 9 
10 a= 5
11 b = 4
12 
13 a,b = b,a
14 print(a,b)

 

 字典的嵌套

  

dic = {'name_list':['张三','lisi','隔壁王'],
        'dic2':{'name':'太白','age':12}}
# 1 ,给列表追加一个元素:'旺旺'
dic['name_list'].append('汪汪')
print(dic)
# ,2,给列表lisi全部大写
dic['name_list'][1] = dic['name_list'][1].upper()
print(dic)
# 3,给dic2 对应的字典添加一个键值对:hobby:girl.
dic ['dic2']['sex'] = 'girl'
print (dic)

 

 fromkey

对于可变的列表,内存地址指向的是列表,所以列表里面的内容改变,并不会引起对应值的改变

dic = dict.fromkeys(['barry','alex',],[])

print(dic)#{'barry': [], 'alex': []}

dic['barry'].append(666)

print(dic)#{'barry': [666], 'alex': [666]}

对于字符串,整型,指针直接指向的是元素的地址,所以元素改变,所对应的也会改变

dic = dict.fromkeys(['barry','alex'],66)

print(dic)#{'barry': 66, 'alex': 66}
dic['alex']= 1
print(dic)#{'barry': 66, 'alex': 1}

  

  

 

posted on 2018-04-08 20:53  凡夫or俗子  阅读(172)  评论(0编辑  收藏  举报