python list和dict使用笔记
1 list加法
print([]+["55"])
# ['55']
2 dict用dict.get()方法添加元素以及添加list类型元素
dict.get()方法一般用来返回指定键的值,参考https://www.runoob.com/python/att-dictionary-get.html
# dict.get()方法 是用来返回指定键的值
# dict.get(key[, value])
# key -- 字典中要查找的键。
# value -- 可选,如果指定键的值不存在时,返回该默认值value。
tinydict = {'Name': 'Runoob', 'Age': 27}
print ("Age : %s" % tinydict.get('Age'))
# Age : 27
# 没有设置 Sex,也没有设置默认的值,输出 None,反正不会报错
print ("Sex : %s" % tinydict.get('Sex'))
# Sex : None
# 没有设置 Salary,输出设置的值 0.0
print ('Salary: %s' % tinydict.get('Salary', 0.0))
# Salary: 0.0
# get() 方法 和 dict[key] 访问元素区别
# get(key) 方法在 key(键)不在字典中时,可以返回默认值 None 或者设置的默认值。
# dict[key] 在 key(键)不在字典中时,会触发 KeyError 异常。
dict.get()方法 也可以用来 给 dict 添加元素
history = {}
dic_1 = {"Name": "HaiCoder", "Age": 100, "Score": 99.5}
for name, metric in dic_1.items():
history.get(name, [])
print(history)
print("---------------------")
for name, metric in dic_1.items():
history[name] = history.get(name, [])
print(history)
print("---------------------")
for name, metric in dic_1.items():
history[name] = history.get(name, [metric])
print(history)
print("---------------------")
for name, metric in dic_1.items():
history[name] = history.get(name, []) + [metric]
print(history)
print("---------------------")
for name, metric in dic_1.items():
history[name] # 语法错误,不成立
# 返回如下
{}
---------------------
{'Name': [], 'Age': [], 'Score': []}
---------------------
{'Name': [], 'Age': [], 'Score': []}
---------------------
{'Name': ['HaiCoder'], 'Age': [100], 'Score': [99.5]}
---------------------
以下为进阶版
import pandas as pd
history = {}
dic_1 = {"Name": "HaiCoder", "Age": 100, "sex":"girl", "Score":99.5}
epochs = 10
for epoch in range(1, epochs + 1):
dic_1["epoch"] = epoch
for key, value in dic_1.items():
history[key] = history.get(key, []) + [value]
print(history)
print("----------------------------------------")
print(pd.DataFrame(history))
# 结果为
{'Name': ['HaiCoder', 'HaiCoder', 'HaiCoder', 'HaiCoder', 'HaiCoder', 'HaiCoder', 'HaiCoder', 'HaiCoder', 'HaiCoder', 'HaiCoder'], 'Age': [100, 100, 100, 100, 100, 100, 100, 100, 100, 100], 'sex': ['girl', 'girl', 'girl', 'girl', 'girl', 'girl', 'girl', 'girl', 'girl', 'girl'], 'Score': [99.5, 99.5, 99.5, 99.5, 99.5, 99.5, 99.5, 99.5, 99.5, 99.5], 'epoch': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}
----------------------------------------
Name Age sex Score epoch
0 HaiCoder 100 girl 99.5 1
1 HaiCoder 100 girl 99.5 2
2 HaiCoder 100 girl 99.5 3
3 HaiCoder 100 girl 99.5 4
4 HaiCoder 100 girl 99.5 5
5 HaiCoder 100 girl 99.5 6
6 HaiCoder 100 girl 99.5 7
7 HaiCoder 100 girl 99.5 8
8 HaiCoder 100 girl 99.5 9
9 HaiCoder 100 girl 99.5 10
这么做的原因:列表list中元素是顺序的,但是字典dict则是乱序的。当然也可以用collections.OrderedDict() 顺序字典。参考:https://blog.youkuaiyun.com/qq_42184799/article/details/86311804
3 OrderedDict有序字典使用及其和Dict的对比
注意:OrderedDict 和 Dict 的用法一致,甚至Dict也是有序的,只是为了保险,使用OrderedDict
import collections
dic_1 = {"Name": "HaiCoder", "Age": 100, "sex":"girl"} #
dic_2 = {"Score":99.5}
print(dic_1)
print("----------------------------------------")
print(dic_1.items())
print("----------------------------------------")
for k in dic_1.items():
print(k) # 对字典的遍历
print(type(k))
print("----------------------------------------")
for k in dic_1:
print(k) # 对有序字典的每次遍历,结果都一样
print(type(k))
print("----------------------------------------")
d3 = collections.OrderedDict(dic_2, **dic_1)
print(d3)
print("----------------------------------------")
print(d3.items())
print("----------------------------------------")
d4 = collections.OrderedDict(dic_1, **dic_2)
print(d4)
print("----------------------------------------")
d5 = collections.OrderedDict(dic_1)
print(d5)
print("----------------------------------------")
for k in d3.items():
print(k) # 对有序字典的每次遍历,结果都一样
print(type(k))
print("----------------------------------------")
for k in d3:
print(k) # 对有序字典的每次遍历,结果都一样
print(type(k))
print("----------------------------------------")
for k,v in d3.items():
print (k,v) # 对有序字典的每次遍历,结果都一样
print("----------------------------------------")
for k,v in d4.items():
print (k,v) # 对有序字典的每次遍历,结果都一样
# 返回
{'Name': 'HaiCoder', 'Age': 100, 'sex': 'girl'}
----------------------------------------
dict_items([('Name', 'HaiCoder'), ('Age', 100), ('sex', 'girl')])
----------------------------------------
('Name', 'HaiCoder')
<class 'tuple'>
('Age', 100)
<class 'tuple'>
('sex', 'girl')
<class 'tuple'>
----------------------------------------
Name
<class 'str'>
Age
<class 'str'>
sex
<class 'str'>
----------------------------------------
OrderedDict([('Score', 99.5), ('Name', 'HaiCoder'), ('Age', 100), ('sex', 'girl')])
----------------------------------------
odict_items([('Score', 99.5), ('Name', 'HaiCoder'), ('Age', 100), ('sex', 'girl')])
----------------------------------------
OrderedDict([('Name', 'HaiCoder'), ('Age', 100), ('sex', 'girl'), ('Score', 99.5)])
----------------------------------------
OrderedDict([('Name', 'HaiCoder'), ('Age', 100), ('sex', 'girl')])
----------------------------------------
('Score', 99.5)
<class 'tuple'>
('Name', 'HaiCoder')
<class 'tuple'>
('Age', 100)
<class 'tuple'>
('sex', 'girl')
<class 'tuple'>
----------------------------------------
Score
<class 'str'>
Name
<class 'str'>
Age
<class 'str'>
sex
<class 'str'>
----------------------------------------
Score 99.5
Name HaiCoder
Age 100
sex girl
----------------------------------------
Name HaiCoder
Age 100
sex girl
Score 99.5
进阶版,,,
import pandas as pd
import collections
history = collections.OrderedDict()
dic_1 = collections.OrderedDict({"Name": "HaiCoder", "Age": 100, "sex":"girl", "Score":99.5})
i = 0
dic_1["epoch"] = i
for key, value in dic_1.items():
history[key] = history.get(key, []) + [value]
i = i + 1
print(history)
print("----------------------------------------")
print(pd.DataFrame(history))
print("----------------------------------------")
epochs = 10
for epoch in range(1, epochs + 1):
dic_1["epoch"] = epoch
for key, value in dic_1.items():
history[key] = history.get(key, []) + [value]
print(history)
print("----------------------------------------")
print(pd.DataFrame(history))
# 返回
OrderedDict([('Name', ['HaiCoder']), ('Age', [100]), ('sex', ['girl']), ('Score', [99.5]), ('epoch', [0])])
----------------------------------------
Name Age sex Score epoch
0 HaiCoder 100 girl 99.5 0
----------------------------------------
OrderedDict([('Name', ['HaiCoder', 'HaiCoder', 'HaiCoder', 'HaiCoder', 'HaiCoder', 'HaiCoder', 'HaiCoder', 'HaiCoder', 'HaiCoder', 'HaiCoder', 'HaiCoder']), ('Age', [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]), ('sex', ['girl', 'girl', 'girl', 'girl', 'girl', 'girl', 'girl', 'girl', 'girl', 'girl', 'girl']), ('Score', [99.5, 99.5, 99.5, 99.5, 99.5, 99.5, 99.5, 99.5, 99.5, 99.5, 99.5]), ('epoch', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])])
----------------------------------------
Name Age sex Score epoch
0 HaiCoder 100 girl 99.5 0
1 HaiCoder 100 girl 99.5 1
2 HaiCoder 100 girl 99.5 2
3 HaiCoder 100 girl 99.5 3
4 HaiCoder 100 girl 99.5 4
5 HaiCoder 100 girl 99.5 5
6 HaiCoder 100 girl 99.5 6
7 HaiCoder 100 girl 99.5 7
8 HaiCoder 100 girl 99.5 8
9 HaiCoder 100 girl 99.5 9
10 HaiCoder 100 girl 99.5 10
注意下面的报错
import pandas as pd
import collections
history = collections.OrderedDict()
dic_1 = collections.OrderedDict({"Name": "HaiCoder", "Age": 100, "sex":"girl", "Score":99.5})
i = 0
for key, value in dic_1.items():
history["epoch"] = i # 这个操作导致history字典中"epoch"键对应的值是数字类型int
history[key] = history.get(key, []) + [value]
print(history)
print("----------------------------------------")
print(pd.DataFrame(history))
print("----------------------------------------")
epochs = 10
for epoch in range(1, epochs + 1):
dic_1["epoch"] = epoch # 这个操作使得dic_1字典中"epoch"键对应的值是数字类型int
for key, value in dic_1.items():
history[key] = history.get(key, []) + [value] # 但是这个操作history字典中"epoch"键对应的值是列表list类型,会与前面已经定义好的history字典中已经存在的epoch"键对应的int类型值起冲突
print(history)
print("----------------------------------------")
print(pd.DataFrame(history))
# 返回
OrderedDict([('epoch', 0), ('Name', ['HaiCoder']), ('Age', [100]), ('sex', ['girl']), ('Score', [99.5])])
----------------------------------------
epoch Name Age sex Score
0 0 HaiCoder 100 girl 99.5
----------------------------------------
Traceback (most recent call last):
File "D:/Resource_Learning/LIWEI/Example.py", line 183, in <module>
history[key] = history.get(key, []) + [value]
TypeError: unsupported operand type(s) for +: 'int' and 'list'
# 报错原因
因为前面 history["epoch"] = i # 这个操作导致history字典中"epoch"键对应的值是数字类型int
而后面 history[key] = history.get(key, []) + [value] # 但是这个操作history字典中"epoch"键对应的值是列表list类型,会与前面已经定义好的history字典中已经存在的epoch"键对应的int类型值起冲突
这个报错在dict中一样会出现
OrderedDict和Dict也可以混用,所以对排序精度要求没那么严格,就直接用dict()吧
import collections
history = collections.OrderedDict()
dic_1 = collections.OrderedDict({"Name": "HaiCoder", "Age": 100, "sex":"girl"})
dic_2 = {"Score":99.5}
dic_3 = collections.OrderedDict({"Score":99.5})
print(collections.OrderedDict(dic_1,**dic_2))
print("----------------------------------------")
print(dict(dic_1,**dic_2))
print("----------------------------------------")
print(dict(dic_1,**dic_3))
print("----------------------------------------")
print(collections.OrderedDict(dic_1,**dic_3))
print("----------------------------------------")
# 返回
OrderedDict([('Name', 'HaiCoder'), ('Age', 100), ('sex', 'girl'), ('Score', 99.5)])
----------------------------------------
{'Name': 'HaiCoder', 'Age': 100, 'sex': 'girl', 'Score': 99.5}
----------------------------------------
{'Name': 'HaiCoder', 'Age': 100, 'sex': 'girl', 'Score': 99.5}
----------------------------------------
OrderedDict([('Name', 'HaiCoder'), ('Age', 100), ('sex', 'girl'), ('Score', 99.5)])
----------------------------------------