2

basically I'm just parsing a JSON file containing informations about several movies and save some of them in a different dictionary for later use

example: not all movies have a description, I'm using a try/except to handle the "keyError" that appears when there is no description in the json, is there a better way to do it?

for movie in json:
    # other entries
    try:
        description = {"description": movie_details['Description']}
    except KeyError:
        description = {"description": ""}
    # other entries
    try:
        other_value = {"other_value": movie_details["other_value"]
    except KeyError:
        other_value = {"other_value": ""}

this seems to me very "dirty", if you have some tip to write a cleaner code would be awesome

Thanks

S.C.A
  • 87
  • 9
  • 2
    You could use .get, see [here](https://stackoverflow.com/questions/11041405/why-dict-getkey-instead-of-dictkey) – Dani Mesejo Sep 05 '19 at 15:08
  • 1
    if `movie_details` is a `dict` you can ask before accessing `'value' in movie_details` – dcg Sep 05 '19 at 15:09

2 Answers2

2

One way is to use .get() with sentinal value:

for movie in json:
    description = {'description': movie_details.get('Description', '')}
    # and similarly for other values...

This makes sure that if the key is not found, the sentinal value is used.

I'm not that sure if you needed to use movie_details or movie inside the loop. I think you meant the latter.

Austin
  • 25,759
  • 4
  • 25
  • 48
1

one way is to convert movie_details to a collections.defaultdict

movie_details = collections.defaultdict(str,movie_details)

if a key is not found, the specialized dictionary object calls str to create a new key (empty string)

Once you've done this, just use it like a normal dict access:

description = {'description': movie_details['Description']}
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219