python数据类型之字典(一)

时间:2023-02-07 13:02:32
>>> dInfo = dict(Wangdachui=3000,Niuyun=2000,Linling=4500,Tianqi=8000)
>>> dInfo
{'Wangdachui': 3000, 'Niuyun': 2000, 'Linling': 4500, 'Tianqi': 8000}

字典定义:

字典是一种映射类型,是由key(键)和value(值)组成的键值对,key是不可变类型,可以是数字、字符串、元组等等

创建字典:

1、直接创建:

ainfo = {'Wangdachui':3000,'Niuyun':2000.'Linling':4500,'Tianqi':8000}

2、间接创建:

>>> info = [('Wangdachui',3000),('Niuyun',2000),('Linling',4500),('Tianqi',8000)]
>>> binfo = dict(info)
>>> binfo
{'Wangdachui': 3000, 'Niuyun': 2000, 'Linling': 4500, 'Tianqi': 8000}
>>> info = [['Wangdachui',3000],['Niuyun',2000],['Linling',4500],['Tianqi',8000]]
>>> dict(info)
{'Wangdachui': 3000, 'Niuyun': 2000, 'Linling': 4500, 'Tianqi': 8000}
>>> dInfo = dict(Wangdachui=3000,Niuyun=2000,Linling=4500,Tianqi=8000)
>>> dInfo
{'Wangdachui': 3000, 'Niuyun': 2000, 'Linling': 4500, 'Tianqi': 8000}
>>> info = (('Wangdachui',3000),('Niuyun',2000),('Linling',4500),('Tianqi',8000))
>>> dict(info)
{'Wangdachui': 3000, 'Niuyun': 2000, 'Linling': 4500, 'Tianqi': 8000}
>>> info = (['Wangdachui',3000],['Niuyun',2000],['Linling',4500],['Tianqi',8000])
>>> dict(info)
{'Wangdachui': 3000, 'Niuyun': 2000, 'Linling': 4500, 'Tianqi': 8000}

上面五种方法,有四种其实是列表+元组的排列组合。。

如何将value设为默认值?

>>> aDict = {}.fromkeys(('Wangdachui','Niuyun','Linling','Tianqi'),3000)
>>> aDict
{'Wangdachui': 3000, 'Niuyun': 3000, 'Linling': 3000, 'Tianqi': 3000}

注意这里fromkeys的第一个元素必须是不可变的元组,不能是可变的列表

如何将两个列表组合成一个字典?  

>>> names = ['Wangdachui','Niuyun','Linling','Tianqi']
>>> salaries = [3000,2000,4500,8000]
>>> dict(zip(names,salaries))
{'Wangdachui': 3000, 'Niuyun': 2000, 'Linling': 4500, 'Tianqi': 8000}

创建字典案例:

给出一个列表的数据,包括公司代码,公司名称和股票价格

>>> plist = [('AXP', 'American Express Company', '86.40'),
('BA', 'The Boeing Company', '122.64'),
('CAT', 'Caterpillar Inc.', '99.44'),
('CSCO', 'Cisco Systems,Inc.', '23.78'),
('CVX', 'Chevron Corporation', '115.91')]

如何构造公司代码和股票价格的字典

{'AXP': '86.40', 'BA': '122.64', 'CAT': '99.44', 'CSCO': '23.78', 'CVX': '115.91'}

这里有两种方法:

1、用for循环

>>> plist
[('AXP', 'American Express Company', '86.40'), ('BA', 'The Boeing Company', '122.64'), ('CAT', 'Caterpillar Inc.', '99.44'), ('CSCO', 'Cisco Systems,Inc.', '23.78'), ('CVX', 'Chevron Corporation', '115.91')]
>>> alist =[]
>>> blist =[]
>>> for i in range(5):
aStr = plist[i][0]
bStr = plist[i][2]
alist.append(aStr)
blist.append(bStr) >>> aDict = dict(zip(alist,blist))
>>> aDict
{'AXP': '86.40', 'BA': '122.64', 'CAT': '99.44', 'CSCO': '23.78', 'CVX': '115.91'}

2、用生成键值对的方式

>>> plist
[('AXP', 'American Express Company', '86.40'), ('BA', 'The Boeing Company', '122.64'), ('CAT', 'Caterpillar Inc.', '99.44'), ('CSCO', 'Cisco Systems,Inc.', '23.78'), ('CVX', 'Chevron Corporation', '115.91')]
>>> aDict ={}
>>> for data in plist:
aDict[data[0]] = data[2] >>> aDict
{'AXP': '86.40', 'BA': '122.64', 'CAT': '99.44', 'CSCO': '23.78', 'CVX': '115.91'}