Ali Hamdan Ali Hamdan - 4 months ago 8
JSON Question

Leaving dictionary field empty if no value is there

My last value variable will contain an empty string if there is no "Type2" value, if this occurs i want the dictionary for that KEY not to contain a "Type2" key:value.

How would i go about that?

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 }})

Answer

Enclosing that portion in an if should work for you.

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})