Python中字典

字典

dict1={}
print("dict1:  ",dict1)

dict1.get("name","001")
print("dict1:  ",dict1)
print("dict1:  ",dict1.get("name","001"))


dict2={"name":"sally","age":"19",0:"yes"}
#更新字典
dict1.update(dict2)
print("dict1:  ",dict1)

#和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
dict1.setdefault("money","1000")
print("dict1:  ",dict1)

#items()以列表返回可遍历的(键, 值) 元组数组
for i in dict1.items():
    print("遍历字典元素:",i)

#分别返回所有键,所有值
print("dict1:  ",dict1.keys())
print("dict1:  ",dict1.values())

#随机返回并删除字典中的一对键和值
print("dict1:  ",dict1.popitem())


print("dict1:  ",dict1.keys())
print("dict1:  ",dict1.values())

运行结果

dict1:   {}
dict1:   {}
dict1:   001
dict1:   {'name': 'sally', 'age': '19', 0: 'yes'}
dict1:   {'name': 'sally', 'age': '19', 0: 'yes', 'money': '1000'}
遍历字典元素: ('name', 'sally')
遍历字典元素: ('age', '19')
遍历字典元素: (0, 'yes')
遍历字典元素: ('money', '1000')
dict1:   dict_keys(['name', 'age', 0, 'money'])
dict1:   dict_values(['sally', '19', 'yes', '1000'])
dict1:   ('money', '1000')
dict1:   dict_keys(['name', 'age', 0])
dict1:   dict_values(['sally', '19', 'yes'])

Process finished with exit code 0

展开阅读全文

没有更多推荐了,返回首页