1.dict表现形式及其特点

1.1.dict表现形式为

  1. dict使用{'key':'value'}形式表示

1.2.dict特点

1、dict中的key值为不可变数据类型,且具有唯一性
2、dict为无序类型

2.增加元素

  1. score = {'chinese':86, 'mathematics':120, 'english':103}
  2. # 添加元素(添加键対值)
  3. score['history'] = 100
  4. print(score) # 输出结果为:{'chinese': 86, 'mathematics': 120, 'english': 103, 'history': 100}

3.删除元素

  1. score = {'chinese':86, 'mathematics':120, 'english':103 'history': 100}
  2. # 删除键対值
  3. del score['mathematics']
  4. print(score) # 输出结果为:{'chinese': 86, 'english': 103, 'history': 100}

4.修改元素

  1. score = {'chinese':86, 'mathematics':120, 'english':103}
  2. # 修改dict值
  3. score['chinese'] = 150
  4. print(score) # 输出结果为:{'chinese': 150, 'mathematics': 120, 'english': 103}

5.查询定位元素

  1. score = {'chinese': 150, 'english': 103, 'history': 100}
  2. # 查询
  3. print(score['chinese']) # 输出结果:150

6.遍历dict

1.遍历所有的键対值:for key,value in dict.items():

  1. score = {'chinese': 150, 'english': 103, 'history': 100}
  2. # 遍历所有的键対值
  3. for key, value in score.items():
  4. print(key,value)
  5. # 输出结果为:
  6. chinese 150
  7. english 103
  8. history 100

2.遍历dict中的键

  1. score = {'chinese': 150, 'english': 103, 'history': 100}
  2. # 遍历dict中的所有的键
  3. for key in score.keys():
  4. print(key)

3.遍历dict中的值

  1. score = {'chinese': 103, 'english': 103, 'history': 100}
  2. # 遍历dict中的所有的值
  3. for value in score.values():
  4. print(value)
  5. # 结果:
  6. 103
  7. 103
  8. 100
  9. # 去重
  10. for value in set(score.values()):
  11. print(value)
  12. # 结果:
  13. 100
  14. 103

4.按顺序大小输出结果

  1. score = {'chinese':86, 'mathematics':103, 'english':103}
  2. for value in sorted(set(score.values())):
  3. print(value)
  4. #结果:
  5. 86
  6. 103

7.总结

python_dict - 图1