!
也想出现在这里? 联系我们
广告位
当前位置:首页>开发>其他开发实例>Python字典的使用方法

Python字典的使用方法

# 字典是一个无序、可变和有索引的集合

# thisdict = {

# 'brand': 'Porsche',

# 'model': '911',

# 'year': 1963

# }

# print(thisdict)

# 获取 "model" 键的值

# x = thisdict['model']

# x = thisdict.get('model')

# print(x)

# 改变year的值

# thisdict['year'] = 2022

# print(thisdict)

# 遍历字典

# for x in thisdict:

# # 打印所有键名

# print(x)

# # 打印所有的值

# print(thisdict[x])

# 返回所有的值

# for x in thisdict.values():

# print(x)

# 遍历键和值

# for x, y in thisdict.items():

# print(x, y)

# 检查键是否存在

# if 'model' in thisdict:

# print('Yes')

# 获取字典长度

# print(len(thisdict))

# 添加新的项目

# thisdict['color'] = 'red'

# print(thisdict)

# 删除项目

# thisdict.pop('model') # 指定键名删除

# thisdict.popitem() # 删除最后一个(在 3.7 之前的版本中,删除随机项目)

# del thisdict['model'] # del 关键字删除具有指定键名的项目

# del thisdict # del 关键字也可以完全删除字典

# thisdict.clear() # clear() 关键字清空字典

# print(thisdict)

# 复制字典

# 不能 dict2 = dict1 来复制字典

# 这样修改值都会发生变化

# thisdict = {

# 'name':'程坊村',

# 'address':'枫港乡',

# 'age':10

# }

# mydict = thisdict.copy()

# mydict = dict(thisdict)

# print(mydict)

# 嵌套字典

# myfamily = {

# "child1" : {

# "name" : "Phoebe Adele",

# "year" : 2002

# },

# "child2" : {

# "name" : "Jennifer Katharine",

# "year" : 1996

# },

# "child3" : {

# "name" : "Rory John",

# "year" : 1999

# }

# }

# print(myfamily)

# child1 = {

# "name" : "Phoebe Adele",

# "year" : 2002

# }

# child2 = {

# "name" : "Jennifer Katharine",

# "year" : 1996

# }

# child3 = {

# "name" : "Rory John",

# "year" : 1999

# }

# myfamily = {

# "child1" : child1,

# "child2" : child2,

# "child3" : child3

# }

# print(myfamily)

# dict() 构造函数

# thisdict = dict(name='abc', model=911, year=2022)

# print(thisdict)

# 创建拥有 3 个键的字典,值均为 0

# dict.fromkeys(keys, value)

# x = ('key1', 'key2', 'key3')

# y = 0

# thisdict = dict.fromkeys(x, y)

# 未指定值就为None

# thisdict = dict.fromkeys(x)

# print(thisdict)

# car = {

# 'name':'byd',

# 'model':'haibao',

# 'year':2022

# }

# x = car.setdefault('model')

# print(x)

# 如果没有键值会插入字典

# x = car.setdefault('color','red')

# print(car)

# 向字典插入项目

# car.update({'color':'red'})

# print(car)

# langs = {

# 'jen':'python',

# 'sarah':'c',

# 'edward':'ruby',

# 'phil':'php',

# 'cjl':'python'

# }

# 遍历所有的键

# for name in sorted(langs.keys()):

# print('Hello '+ name)

# 遍历所有的值

# for lang in langs.values():

# print(lang)

# 去除重复的值

# for lang in set(langs.values()):

# print(lang)

给TA打赏
共{{data.count}}人
人已打赏
其他开发实例

Python列表使用方法

2023-1-5 17:02:04

其他开发实例

Python编程中的print详细使用方法

2023-1-5 17:02:46

声明 本站上的部份代码及教程来源于互联网,仅供网友学习交流,若您喜欢本文可附上原文链接随意转载。无意侵害您的权益,请发送邮件至 [email protected] 或点击右侧 私信:林沐阳 反馈,我们将尽快处理。
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索