python中定义空字典,为何要判断字典是否为空,并进行判断

1,创建一个空的字典,为什么要判断里面可以是否有制定的key?,

先定义一个字典对象

data_dict = {}
for line in data_lines:
year = int(line.split(",")[0]) # 年份
country = line.split(",")[1] # 国家
gdp = float(line.split(",")[2]) # gdp数据
# 如何判断字典里面有没有指定的key呢?
try:
data_dict[year].append([country, gdp])
except KeyError:
data_dict[year] = []
data_dict[year].append([country, gdp])

因为data_dict[year].append([country, gdp])这行代码是直接默认 有yearkey,并且是一个列表
如果没有的话,程序就会报错,所以要先判断是否有该key,如果有后续append操作才能正常进行

for datas in data_dict:
   if 'year ' in datas:


这个样子可以判断字典里是否存在year字段存在

字典的get方法,有值返回该值,没有值,返回None,
你对其做判断就好了


data = {
    "name": '测试'
}
print(data.get('name'))