如果没有值,则将字典字段留空

时间:2016-07-28 15:56:57

标签: python json python-2.7 dictionary

如果没有“Type2”值,我的最后一个值变量将包含一个空字符串,如果发生这种情况,我希望该KEY的字典不包含“Type2”键:value。

我该怎么做?

pokemon_name = json['Items'][i]['Pokemon']['UniqueId'][14:]     
pokemon_type_one = json['Items'][i]['Pokemon']['Type1'][13:]
pokemon_type_two = json['Items'][i]['Pokemon']['Type2'][13:] if 'Type2' in json['Items'][i]['Pokemon'] else ''

pokeD.update({pokemon_name: {'Type1' : pokemon_type_one, 'Type2' : pokemon_type_two }})

1 个答案:

答案 0 :(得分:0)

将该部分包含在if中应该适合您。

pokemon_name = json['Items'][i]['Pokemon']['UniqueId'][14:]     
pokemon_type_one = json['Items'][i]['Pokemon']['Type1'][13:]
if 'Type2' in json['Items'][i]['Pokemon']:
    pokemon_type_two = json['Items'][i]['Pokemon']['Type2'][13:] 
    pokeD.update({pokemon_name: {'Type1' : pokemon_type_one, 'Type2' : pokemon_type_two }})
else:
    pokeD.update({pokemon_name: {'Type1' : pokemon_type_one})