这是我的代码。我只想在名为" country"的字典中记录该值。当键,字典中不存在值。为此,我正在检查关键字不在(第二行代码)。但是,它不起作用。即使字典中存在密钥,它也会更新值。任何帮助都会非常感激。
df = pd.DataFrame()
country = dict()
for file in allFiles:
df = pd.read_excel(file,'Internal', skiprows = 7)
print ("file name is " + file)
if(df.loc[1][0] == "Country:"):
key = df.loc[1][1]
value = df.loc[2][1]
else:
key = df.loc[2][1]
value = df.loc[1][1]
print ('key is ' , key)
print ('value is ' , value)
try:
print (df.loc[47][2], df.loc[47][3])
print (df.loc[49][2], df.loc[49][3])
except Exception as inst:
print (type(inst))
print (inst.args)
print (inst)
if ((key not in country) or (value != 'nan')):
country[key] = value
答案 0 :(得分:4)
从
改变你的状况# Even if 'key' was already in 'country', If (value != 'nan')
# evaluated to 'True', the update will happen
if ((key not in country) or (value != 'nan')):
到
# Do not update unless 1- the key does not exist AND 2- value is not 'nan'
if (key not in country) and (value != 'nan'):
由于value
(很可能)不是nan
,因此记录将始终更新。