Python数据结构基础(一)——字典(Dictionary)

版权声明:本文版权归作者所有,未经允许不得转载! https://blog.csdn.net/m0_37827994/article/details/86491141

四、字典

字典是保存“关键字-对应值”的Python对象。在下面的示例字典中,关键字是“name”和“eye_color”变量。它们每个都有一个对应的值。字典不能有两个相同的关键字。

  • 字典(dictionaries)用 { } 来装值
  • 字典(dictionaries)中的关键字对应的值都要用双引号引起来

1、创建一个字典

# Creating a dictionary
goku = {"name": "Goku",
        "eye_color": "brown"}
print (goku)
print (goku["name"])
print (goku["eye_color"])

输出结果:

{'name': 'Goku', 'eye_color': 'brown'}
Goku
brown

2、更改字典中关键字对应的值

# Changing the value for a key
goku["eye_color"] = "green"
print (goku)

输出结果:

{'name': 'Goku', 'eye_color': 'green'}

3、加入一个新的关键字-对应值 配对

# Adding new key-value pairs
goku["age"] = 24
print (goku)

输出结果:

{'name': 'Goku', 'eye_color': 'green', 'age': 24}

4、字典的长度

# Length of a dictionary
print (len(goku))

输出结果:

3

猜你喜欢

转载自blog.csdn.net/m0_37827994/article/details/86491141
今日推荐