Python——字典

什么是字典?

        有时候我们需要存储一组相关党得数据的时候,比如要存储一个人的信息,那么有user_name, age, birthday 等,如果这些信息都存储在列表中,比如[ 'user_name' , 'age' , 'birthday'] 那么用起来可能不是很方便。比较方便的操作是,我直接通过user_name这个key就可以拿到这个值,我通过user_name就可以给这个key设置值值,那么就可以通过字典的方式实现我们的需求。

字典基础

1.创建字典:我们可以通过两种方式创建字典:

        person = { " user_name" :'python' ,'age' : 19}

或者是使用dirc函数

        person =  dict(username = 'python' ,age = 19)

# 字典是个什么 key : value

# 字典如何定义
#定义一个空字典 dict
student_dict = {}
print(student_dict)
print(type(student_dict))

#
student_dict1 = {
    "user_name": "Micheal",
    "age": 18,
    "birthday": "1017"
}

print(student_dict1["age"])

student_dict2 = {
    "user_name": "Jack",
    "age": 19,
    "birthday": "1018"
}

student_list3 = [student_dict1, student_dict2]
print(student_list3)
for obj in student_list3:
    print(obj["age"])




2.基本操作

        len(d):返回字典的键值对的长度

        d[k]:获取k这个key对应的值

        d[k] = v:设置键为k的值v ,如果字典中不存在键为k的这一项,那么自动的添加进去

        k   in   d :检查d这个字典中是否包含键为k的这一项

        字典中的键可以是任意的不可变类型,比如:浮点类型、整形、字符串




# 字典是个什么 key : value

# 字典如何定义
#定义一个空字典 dict
student_dict = {}
print(student_dict)
print(type(student_dict))

#
student_dict1 = {
    "user_name": "Micheal",
    "age": 18,
    "birthday": "1017"
}

print(student_dict1["age"])

student_dict2 = {
    "user_name": "Jack",
    "age": 19,
    "birthday": "1018"
}


# key : value
print("*" * 50)
print(len(student_dict1))

#
student_dict1["age"] = 20
print(student_dict1)
print(student_dict1["user_name"])

if "user_name1" in student_dict1:
    print("在")
else:
    print("不在")


#
student_dict3 = dict(
    user_name="Micheal",
    age=18,
    birthday="1017",
)
print(student_dict3)

student_dict2 = {
    "user_name": "Jack",
    "age": 19,
    "birthday": "1018"
}


字典的常用方法:

1.clear:清除字典中所有的项

        a = {”user_name" : 'python' , 'age' : 19}

        print(a)

        a.clear()

        print(a)

2.get:访问字典中那个键对应的那个值,这个方法不会抛出异常

        a = { "user_name" : 'python' , 'age' : 19}

        username = a.get('username')

        print(username)

        city = a.get('city') #获取到的是一个None

        #也可以指定一个,在没有获取到这个值时候的默认值

        city = a.get('city','changsha') # 返changsha

        city = a[ 'city' ] #抛出异常

3.pop:用来获得对应于给定键的值,然后将这个键和值的项从字典中删除。会返回这个值

        d = { 'x' : 1 , 'y' : 2}

        d.pop('x')

4.update:用一个字典更新另外一个字典,如果碰到相同的键,则会覆盖。

        a = { ‘url' : 'http://www.baidu.com/' ,'title' : "baidu"}

        b = { "url" : "http://www.google.com/",'new_value' : "new_value"}

        a.update(b)

        print(a)

第一种:

第二种:

第三种:

第四种:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会飞的鱼-blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值