字典就是一个关联数组和散列表,由键和值组成的,即就是键/值的集合,通过键的索引获取值!在大括号{}放入值就可以创建字典。
stock = {
"name" : "GOOG",
"shares": 100,
"price" : 490.10
}
1.9.1通过索引键获取值
name = stock["name"]
print("name= %s" %name)
value = stock["shares"]*stock["price"]
print("name= %0.2f" %value)
输出结果:
name= GOOG
name= 49010.00
1.9.2 修改与插入对象
stock["shares"] = 75 #修改
stock["date"] = "June 7,2018" #插入
print("stock['shares']= %s" %stock["shares"])
print("stock['date']= %s" %stock["date"])
输出结果:
stock['shares']= 75
stock['date']= June 7,2018
1.9.3 创建空字典
prices = {} #一个空字典
prices = dict()#一个空字典
1.9.4 测试某个内容是不是字典成员
prices ={
"GOOG":490.10,
"AAPL":123.50,
"IBM":91.50,
"MSFT":52.13
}
方法一
if "SCOX" in prices:
p = prices["SCOX"]
else:
p = 0.0
#方法二
p = prices.get("SCOX",0.0)
syms = list(prices)
print(syms)
输出结果:
['GOOG', 'AAPL', 'IBM', 'MSFT']
del prices["MSFT"]
syms1 = list(prices)
print("%s" %syms1)
输出结果:
['GOOG', 'AAPL', 'IBM']