python的字典

字典和传统意义上的字典完全不是一个概念。python中的字典或者编程中的字典表示的键值对的结合。每个键对应一个值。

# 新建一个字典
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# 打印字典
print(my_dict)

# 向字典里添加内容
my_dict['phone'] = '123-456-7890'

# 打印字典
print(my_dict)

# 删除字典里的第一个元素
del my_dict['name']

# 打印字典
print(my_dict)

# 定义函数 show_dict 用于打印字典
def show_dict(my_dict):
    for key, value in my_dict.items():
        print(key, ':', value)

# 调用函数 show_dict 打印字典
show_dict(my_dict)

展开/折叠结果 {'name': 'John', 'age': 30, 'city': 'New York'}
{'name': 'John', 'age': 30, 'city': 'New York', 'phone': '123-456-7890'}
{'age': 30, 'city': 'New York', 'phone': '123-456-7890'}
age : 30
city : New York
phone : 123-456-7890

评论

发表评论

了解 数据控|突破是我们的每一步 的更多信息

立即订阅以继续阅读并访问完整档案。

继续阅读