python入门(六) 字典&常用方法

2019-11-13  本文已影响0人  淡漠不淡漠

Dictionary(字典)

#!/usr/bin/python3
dic = {'name':'sun', 'age':'22'}

获取字典中的值

#!/usr/bin/python3
dic = {'name':'sun', 'age':'22'}
res = dic['name']
print(res)
#输出结果:sun
#!/usr/bin/python3
dic = {'name':'sun', 'age':'22'}
res = dic['n']
print(res)
#输出结果:报错
Traceback (most recent call last):
  File "text.py", line 3, in <module>
    res = dic['n']
KeyError: 'n'

修改字典

#!/usr/bin/python3
dic = {'name':'sun', 'age':'22'}
dic['name'] = 'hello'
print(dic['name'])
#输出结果:hello

删除字典元素

dic = {'name':'sun', 'age':'22'}
del dic['name'] #删除name属性
print(dic)
#输出结果:{'age': '22'}
#!/usr/bin/python3
dic = {'name':'sun', 'age':'22'}
del dic
print(dic)
#删除了字典所以输出会报错
Traceback (most recent call last):
  File "text.py", line 4, in <module>
    print(dic)
NameError: name 'dic' is not defined
#!/usr/bin/python3
dic = {'name':'sun', 'age':'22'}
dic.clear()  #清空字典
print(dic)
#输出结果:{}

字典常用方法

len(dic) 计算字典中元素的个数

#!/usr/bin/python3
dic = {'Name': 'Zara', 'Age': 7};
print(len(dic)
#输出结果:2

str(dic) 可以把字典转换为字符串

#!/usr/bin/python3
dic = {'Name': 'Zara', 'Age': 7};
print(str(dic))
print('默认类型:',type(dic))
print('转换为字符串:',type(str(dic))
#输出结果:
{'Name': 'Zara', 'Age': 7}
默认类型: <class 'dict'>
转换为字符串: <class 'str'>

字典的内置函数

dic.clear() 删除字典所有元素(同上)

dic.copy() 拷贝一个字典

#!/usr/bin/python3
dic = {'Name': 'Zara', 'Age': 7};
res = dic.copy()
print(res)
#输出结果:{'Name': 'Zara', 'Age': 7}

dic.fromkeys() 创建一个新的字典

#!/usr/bin/python3
dic = {}
keys = ['name', 'age']
dic = dic.fromkeys(keys)
print(dic)
#输出结果:{'name': None, 'age': None}
#!/usr/bin/python3
dic = {}
keys = ['name', 'age']
dic = dic.fromkeys(keys, 1)
print(dic)
#输出结果:{'name': 1, 'age': 1}

dic.get(key) 获取自动中的key对应的value值

#!/usr/bin/python3
dic = {'name':'Ami', 'age': 11}
print(dic.get('name')
#输出结果:Ami

dic.keys() 获取字典中的key值,返回值可以用 for in 输出结果

#!/usr/bin/python3
dic = {'name':'Ami', 'age': 11}
res = dic.values()
for x in res:
    print(x)
#输出结果:
name
age

dic.values() 获取字典中所有的value值

#!/usr/bin/python3
dic = {'name':'Ami', 'age': 11}
res = dic.values()
for x in res:
    print(x)
#输出结果:
Ami
11

dic.setdefault(key,value)

#!/usr/bin/python3
dic = {'name':'Ami', 'age': 11}
res = dic.setdefault('name')
print(res)
#输出结果:Ami
#!/usr/bin/python3
dic = {'name':'Ami', 'age': 11}
res = dic.setdefault('sex', 'f')
print('新的字典为:',dic)
print('返回值为:', res)
#输出结果:
新的字典为: {'name': 'Ami', 'age': 11, 'sex': 'f'}
返回值为: f

dic1.update(dic2) 将dic2更新到dic1

#!/usr/bin/python3
dic1 = {'name':'Ami', 'age': 11}
dic2 = {'sex': 'f'}
dic1.update(dic2)
print('合并后的字典:', dic1)
#输出结果:
合并后的字典: {'name': 'Ami', 'age': 11, 'sex': 'f'}
上一篇下一篇

猜你喜欢

热点阅读