#!/usr/bin/env/python
#-*-coding:utf-8-*-
#Author:LingChongShi #查看源码Ctrl+左键
'''
dict:字典以“{}”包围,以“键:值”数据集合
1、可存储任意类型对象,包括列表
2、无序,数据项可修改
3、键必须为唯一,值必须唯一
'''
Dict={
'name':
'xiaoshao',
'age':20,
'a':1,
'b':2
}
#查看对象的类,或对象具备的功能
print(dir(Dict))
#查看dict类的源码
# print(help(type(Dict)))
'''一、空字典和一个元素的字典建立'''
print(
'建议一个空字典:',{},type({}))
print(
'建立一个空字典:',dict(),type(dict()))
print(
'建立一个元素的字典:',{
'a':1},type({
'a':1
}))
'''二、访问字典中的值'''
print(
'字典按照键获取值:',Dict[
'name'])
'''三、字典中函数'''
print(
'字典的长度:',len(Dict))
print(
'输出字典,以可打印的字符串表示:',str(Dict),type(str(Dict)))
print(
'返回输入的变量类型:',type(Dict))
#Python 的元组内建方法
'''一、删除字典或字典元素'''
Dict1={
'name':
'xiaoshao',
'age':20,
'a':1,
'b':2
}
Dict1.clear()
print(
'删除字典中所有元素:',Dict1,
'删除后字典长度:',len(Dict1))
Dict1={
'name':
'xiaoshao',
'age':20,
'a':1,
'b':2
}
del Dict1[
'a']
print(
'删除字典中键为a的元素:',Dict1)
del Dict1
#del后字典不再存在
# print('删除字典',Dict1)
'''一、复制字典'''
Dict1=
Dict.copy()
print(
'复制字典:',Dict1)
'''二、元组转换成字典'''
tuple=(
'name',
'age',
'address')
print(
'序列:',tuple,type(tuple))
Dict1=dict.fromkeys(tuple)
#创建一个新字典,以序列 seq 中元素做字典的键,value 为字典所有键对应的初始值
print(
'转换后字典:',Dict1)
Dict2=dict.fromkeys(tuple,
'xiaoshao')
#创建一个新字典,以序列 seq 中元素做字典的键,value 为字典所有键对应的初始值
print(
'转换后字典:',Dict2)
'''三、获取字典中键和值'''
print(
'获取字典中键对应值:',Dict.get(
'a'))
print(
'获取字典中键:',Dict.keys(),type(Dict.keys()))
for key
in Dict.keys():
print(
'获取字典中键:',key)
print(
'获取字典中值:',Dict.values(),type(Dict.values()))
for value
in Dict.values():
print(
'获取字典中值:',value)
print(
'获取字典中键对应值:',Dict.setdefault(
'name',-1))
#setdefault(key,default)--->key:查找的键值,default:键不存在时,设置的默认键值
print(
'以列表返回可遍历的(键, 值)元组数组:',Dict.items(),type(Dict.items()))
for key,value
in Dict.items():
print(key,
':',value)
'''五、删除字典中的元素'''
print(
'删除字典中的元素对,返回值为被删除的值:',Dict.pop(
'name',-1))
#pop(key,default)--->key: 要删除的键值 default: 如果没有 key,返回 default 值
print(
'随机返回并删除字典中的一对键和值,如果字典为空,报异常:',Dict.popitem())
'''六、追加字典'''
Dict1={
'name':
'xiaoshao',
'age':20
}
Dict2={
'a':1,
'b':2
}
Dict1.update(Dict2)
print(
'被追加的字典:',Dict1)
print(
'追加的字典:',Dict2)
转载于:https://www.cnblogs.com/sjl179947253/p/7376351.html
转载请注明原文地址: https://win8.8miu.com/read-17084.html