15-字典

2018-10-26  本文已影响5人  努力爬行中的蜗牛
字典的定义

列表是有序对象的集合,字典是无序对象的集合。

#字典是无序的集合
xiaoming = {"name":"小明",
            "age":18,
            "gender":True,
            "height":175,
            "weight":50}
print(xiaoming)
字典的增删改查
#字典是无序的集合
xiaoming = {"name":"小明"}
#取值
print(xiaoming["name"])
#增加、修改
xiaoming["age"] = 18
xiaoming["name"] = "小小明"
print(xiaoming)
#删除
xiaoming.pop("age")
print(xiaoming)
字典的统计、合并、清空
#字典是无序的集合
xiaoming = {"name":"小明",
            "age":18}
#统计键值对数量
print(len(xiaoming))
#合并字典
#注意:如果被合并的字典中包含已经存在的键,会覆盖原有的值
temp_dict = {"height":1.75}
xiaoming.update(temp_dict)
print(xiaoming)
#清空字典
xiaoming.clear()
print(xiaoming)
字典的循环遍历
#字典是无序的集合
xiaoming = {"name":"小明",
            "age":18,
            "hegith":1.75}
for k in xiaoming:
    print(xiaoming[k])

上一篇下一篇

猜你喜欢

热点阅读