Python字典dict的常用方法和函数
2021-03-21 15:26
标签:常用方法 tde seq ems 存在 遍历 字符 删除 for Python字典dict的常用方法和函数 标签:常用方法 tde seq ems 存在 遍历 字符 删除 for 原文地址:https://blog.51cto.com/xxy12345/2544446
dict.clear()
#运行结果{}
print(dict.pop(‘age‘))
print(dict)
#结果18,{‘name‘: ‘Joe‘, ‘height‘: 60}
print(dict.pop(‘agea‘,‘erro‘))
print(dict)
#结果erro,{‘name‘: ‘Joe‘, ‘age‘: 18, ‘height‘: 60}
print(dict.popitem())
print(dict)
#结果(‘height‘, 60),{‘name‘: ‘Joe‘, ‘age‘: 18}
del dict[‘age‘]
print(dict)
#结果{‘name‘: ‘Joe‘, ‘height‘: 60}
dict.__getitem__(‘name‘)
print(dict.get(‘name‘))
#结果Joe
print(dict.get(‘hobby‘))
#结果None
print(dict.get(‘hobby‘,‘basketball‘))
#结果basketball
print(dict.setdefault(‘hobby‘))
print(dict)
#结果None,{‘name‘: ‘Joe‘, ‘age‘: 18, ‘height‘: 60, ‘hobby‘: None}
print(dict.setdefault(‘hobby‘,‘basketball‘))
print(dict)
#结果basketball,{‘name‘: ‘Joe‘, ‘age‘: 18, ‘height‘: 60, ‘hobby‘: ‘basketball‘}
dict.update({‘age‘:20})
print(dict)
#结果{‘name‘: ‘Joe‘, ‘age‘: 20, ‘height‘: 60}
dict.update({‘hobby‘:‘run‘})
print(dict)
#结果{‘name‘: ‘Joe‘, ‘age‘: 18, ‘height‘: 60, ‘hobby‘: ‘run‘}
seq = (‘a‘, ‘b‘, ‘c‘)
print(dict.fromkeys(seq))
#结果{‘a‘: None, ‘b‘: None, ‘c‘: None}
print(dict.fromkeys(seq,‘oh‘))
#结果{‘a‘: ‘oh‘, ‘b‘: ‘oh‘, ‘c‘: ‘oh‘}
print(dict.items())
print(dict.values())
print(dict.keys())
#结果
dict_items([(‘name‘, ‘Joe‘), (‘age‘, 18), (‘height‘, 60)])
dict_values([‘Joe‘, 18, 60])
dict_keys([‘name‘, ‘age‘, ‘height‘])
for i in dict:
print(i)
#结果
name
age
height
#相同效果的遍历如下:
for key in dict.keys():
print(key)
#
for vlaue in dict.values():
print(vlaue)
#结果
Joe
18
60
#10.1输出为元组的方式
for item in dict.items():
print(item)
#结果
(‘name‘, ‘Joe‘)
(‘age‘, 18)
(‘height‘, 60)
#10.2输出为字符串的方式
for key,vlaue in dict.items():
print(key,vlaue)
#结果
name Joe
age 18
height 60
#输出为字符串的另一种方式
for i in dict:
print(i,dict[i])
文章标题:Python字典dict的常用方法和函数
文章链接:http://soscw.com/index.php/essay/67234.html