如何运用Python里的字典Dictionary

2025-11-05 17:08:13

1、新建一个JUPYTER NOTEBOOK文档。

如何运用Python里的字典Dictionary

2、可以先定义一个空集合的字典,然后再慢慢往里面添加关键词和数值。

d = {}

d["Peter"] = 88

d["Ben"] = 18

d["Alice"] = 20

print(d["Peter"])

print(d["Ben"])

print(d["Alice"])

如何运用Python里的字典Dictionary

3、没有定义好的是不能打印出来的,例如如下:

print(d["Apple"])

如何运用Python里的字典Dictionary

4、利用FOR IN 语句打印字典里面的关键词和值。

for key, value in d.items():

    print("key")

    print(key)

    print("value")

    print(value)

如何运用Python里的字典Dictionary

5、可以直接定义字典的内容。

phone_number = {"HE": "73647829874", "SHE": "47381049284", "THEY": "37294856371"}

print(phone_number)

如何运用Python里的字典Dictionary

6、可以改变关键词对应的数值。

phone_number["THEY"] = "WE"

print(phone_number)

如何运用Python里的字典Dictionary

7、通过用LEN可以知道关键词的数量。

len(d)

如何运用Python里的字典Dictionary

8、可以删除指定的关键词和数值。

del phone_number["HE"]

print(phone_number)

如何运用Python里的字典Dictionary

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢