1.定义
eng2sp = {} # 定义空字典 eng2sp[‘one‘] = ‘uno‘ eng2sp[‘two‘] = ‘dos‘ print eng2sp print eng2sp[‘two‘] # 字典查询:通过key查询value eng2sp[2] = ‘hdi‘ # 字典没有顺序 print eng2sp
2.常见操作
inventory = {‘apples‘: 430, ‘bananas‘: 312,‘oranges‘: 525, ‘pears‘: 217} # 修改 inventory[‘bananas‘] = 0 print inventory # 删除 del inventory[‘bananas‘] print inventory # 计数 print len(inventory) # 清空 inventory.clear() print inventory
3.别名和拷贝
inventory = {‘apples‘: 430, ‘bananas‘: 312,‘oranges‘: 525, ‘pears‘: 217} alias = inventory copy1 = inventory.copy() #alias和inventory指向同一个值。而copy1则指向全新的拷贝 alias[‘bananas‘] = 33 print inventory[‘bananas‘] #如果修改alias,inventory也发生变化。 copy1[‘bananas‘] = 56 print inventory[‘bananas‘] #如果修改copy1,inventory则不会发生变化。
4.get用法
letterCounts = {} for letter in "Mississippi": letterCounts[letter] = letterCounts.get (letter, 0) + 1 print letterCounts #打印出每个字母出现的次数
原文:https://www.cnblogs.com/qiuqiu21/p/14116669.html