5-Dictionaries_working_with_key-value_pairs

初始化

student = {‘name’: ‘Dale’, “age”: 18, “courses”: [“math”, “science”], 1: “index”}

正文

index取值

print(student[1])  # key值可以是字符串,也可以是数字
print(student["name"])

get方法

print(student.get("courses"))
# get方法传入不存在的key值,默认返回None,可通过传入第二个参数来指定key值不存在时get方法的return value
print(student.get("phone", "Not Found"))  
# 如果不使用get方法,采用index方式访问,则运行结果为: **KeyError: 'live' **
print(student["live"]) 

updata方法

可以通过给update方法传入一个字典参数,来增加原字典的key-value键值对,或者修改已有的键值对

student.update({"name": "Jane", "age": 28, "phone": "133333"})  
print(student)  # out: {'name': 'Jane', 'age': 28, 'courses': ['math', 'science'], 1: 'index', 'phone': '133333'}

del 函数

通过系统函数del 删除dict中的键值对

del student["age"]
print(student)  # {'name': 'Jane', 'courses': ['math', 'science'], 1: 'index', 'phone': '133333'}

pop方法

通过dict的pop方法删除dict中的键值对,并将该key对应的value以返回值返回

ret=student.pop("phone")
print(ret)  # out: 133333
print(student)  # out: {'name': 'Jane', 'courses': ['math', 'science'], 1: 'index'}

key, value, items

遍历一个dict中的key value 及 items的方式

print(student.items())  # dict_items([('name', 'Jane'), ('courses', ['math', 'science']), (1, 'index')])
student.keys()
student.values()
for key, value in student.items():
     print(key, value)
# out:
# name Jane
# courses ['math', 'science']
# 1 index

特殊的一个例子

for…in… 循环中可以有2个以上的index变量。
多级嵌套的list(比如json格式转化来的数据)也可以用此方式循环访问

test = [['name', 'Jane', 1], ['courses', ['math', 'science'], 2], [1, 'index', 3]]
for index, value, emp in test:
    print(index, value, emp)
 # out:
 # name Jane 1
 # courses ['math', 'science'] 2
 # 1 index 3

引用

本文主要参考下列视频内容,翻译并亲测代码后形成此文,感谢视频作者的无私奉献!
5-Dictionaries_working_with_key-value_pairs

猜你喜欢

转载自blog.csdn.net/Dale1991/article/details/88099897