Konstantin Rusanov
Konstantin Rusanov

Reputation: 6554

KeyError in append dict

I have large peace of data, iterate true this in loop and append values by key:

for q in my_dict:
output.append({"roomsCount": q['roomsCount'], "totalArea": float(q['totalArea']), 
"floorNumber": q['floorNumber'],"price": int(q['bargainTerms']['price']), ...})

Sometimes i got : KeyError: 'roomsCount' or KeyError: 'totalArea' etc. if key doesn't exist.

How i can set default value for any key in case if this key not exist? Without repeat try: except for each of my key:value pairs

Upvotes: 0

Views: 7905

Answers (2)

Raymond Hettinger
Raymond Hettinger

Reputation: 226376

How i can set default value for any key in case if this key not exist?

The dict.setdefault() method is likely what you want here:

d = {'hits': 10, 'gold': 5}
print( d.setdefault('weapons', 0) )
print( d.setdefault('hits', 10) )

Upvotes: 1

Konstantin Rusanov
Konstantin Rusanov

Reputation: 6554

Solved by adding dict.get, thanks for comments. My code

for q in mydict:
        output.append(
            {"roomsCount": q.get('roomsCount', 0), "totalArea": float(q.get('totalArea', 0)), "floorNumber": q.get('floorNumber',0),
             "price": int(q.get('bargainTerms''price',0))...}) 

Upvotes: 0

Related Questions