32

I parsed some JSON data, creating bb_json, and am trying to write CSV data based on it to csv_writer. I have this code:

for product in bb_json['products']:
    row = []

    row.append(product['sku'])
    if product['name']:
        row.append(product['name'])
    else:
        row.append("")
    if product['description']:
        row.append(product['description'])
    else:
        row.append("none")
    row.append(product['image'] + " ")
    if product['manufacturer']:
        row.append(product['manufacturer'])
    else:
        row.append("UNKNOWN")
    row.append(product['upc'])
    row.append(product['department'])
    row.append(product['class'])
    row.append(product['subclass'])
    
    csv_writer.writerow(row)    

But I get a KeyError from the attempts to read data from product, because many of these values are unpopulated. How can I fill in default values in the row?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Kenfucious
  • 397
  • 1
  • 5
  • 9

4 Answers4

78

You can use your_dict.get(key, "default value") instead of directly referencing a key.

Noam Manos
  • 15,216
  • 3
  • 86
  • 85
Stack of Pancakes
  • 1,881
  • 18
  • 23
  • Thanks for assisting. That line would be inserted before the for loop, or iteratively within? – Kenfucious Jul 17 '14 at 21:54
  • 2
    Whenever you'd normally access a key. So when you go to get the product's name instead of `row.append(product['name'])` you would use `row.append(product.get('name', 'value if name key doesn't exist'))` – Stack of Pancakes Jul 17 '14 at 21:57
  • Thanks, that seemed to work!! One final point: I'm now getting a nonetype error for one of the fields (manufacturer). The if clause for 'name' works well, but a similar syntax yields the dreaded KeyError once again. – Kenfucious Jul 17 '14 at 22:36
  • 2
    Don't use `None` for the default value. In your code you're setting it to `""` if the value doesn't exist. So try `row.append(product.get('name', ''))` Which will append the value for `name` if it exists, or an empty string if it doesn't. – Yep_It's_Me Jul 17 '14 at 22:48
  • Notice that "dict" shouldn't be the name of your dictionary, since "dict" is a reserved built-in symbol in Python – Noam Manos Jan 29 '16 at 20:22
9

Don't use the "default" argument name. For example, if we want 1.0 as default value,

rank = dict.get(key, 1.0)

For more details: TypeError: get() takes no keyword arguments

Community
  • 1
  • 1
Serendipity
  • 2,216
  • 23
  • 33
9

If you can't define a default value and want to do something else (or just omit the entry):

if key in dict:
    rank = dict[key]
else:
    # do something or just skip the else block entirely
2

You could use syntax like this: product.get("your field", "default value")

Eugen
  • 2,292
  • 3
  • 29
  • 43