# 小白学 Python（12）：基础数据结构（字典）（上）

## 创建字典

{key1: value1, key2: value2}

dict1 = {'name': 'geekdigging', 'age': 2}
print(dict1)
print(type(dict1))

{'name': 'geekdigging', 'age': 2}


dict2 = {(1, 2, 3): '123', 'name': 'geekdigging', 2: [1, 2, 3]}
print(dict2)
print(type(dict2))

{(1, 2, 3): '123', 'name': 'geekdigging', 2: [1, 2, 3]}


dict3 = dict(name = 'geekdigging', age = 2)
print(dict3)
print(type(dict3))

{'name': 'geekdigging', 'age': 2}


dict3 = dict(1 = 'geekdigging', 2 = 2)

File "D:/Development/Projects/python-learning/base-data-dict/Demo.py", line 13
dict3 = dict(1 = 'geekdigging', 2 = 2)
^
SyntaxError: keyword can't be an expression

## 访问字典中的值

print(dict1['name'])

geekdigging

print(dict1['geekdigging'])

Traceback (most recent call last):
File "D:/Development/Projects/python-learning/base-data-dict/Demo.py", line 18, in
print(dict1['geekdigging'])
KeyError: 'geekdigging'

str = 'geekdigging'

if str in dict1:
print(dict1['geekdigging'])
else:
print('您查询的键', str, '不存在')

您查询的键 geekdigging 不存在

## 添加、删除、更新 字典中的键值对：

# 添加
dict1['a'] = 18
print(dict1)
# 更新
dict1['name'] = 'www.geekdigging.com'
print(dict1)
# 删除
del dict1['a']
print(dict1)

{'name': 'geekdigging', 'age': 2, 'a': 18}
{'name': 'www.geekdigging.com', 'age': 2, 'a': 18}
{'name': 'www.geekdigging.com', 'age': 2}