Python基础语法(四)字典

定义一个字典

{key1:value1,key2:value2}

info = {"name":"laowang","old":18}

添加元素

info = {"name":"laowang","old":18}
info["old"] = 18 #info = {"name":"laowang","old":18}

修改元素

info = {"name":"laowang","old":18}
info["old"] = 20 #{"name":"laowang","old":20}

删除元素

info = {"name":"laowang","old":18}
del info["old"] #{"name":"laowang"}

查询元素

info = {"name":"laowang","old":18}
info.get("name") #laowang
info.get("qq") # 空
info["qq"] #抛出异常

常用属性

len 键值对的个数

info = {"name":"laowang","old":18}
info.len() # 打印信息2

keys 字典中所有的键列表

info = {"name":"laowang","old":18}
info.keys() # 打印信息["name","old"]

values 字典中所有的值列表

info = {"name":"laowang","old":18}
info.values() # 打印信息["laowang",18]

items 字典中所有的键值元组列表

info = {"name":"laowang","old":18}
info.items() # 打印信息[("name","laowang"),("old",18)]

字典中的key不能是列表类型,可以是字符串、数字、元组

你可能感兴趣的:(Python基础语法(四)字典)