chink
chink

Reputation: 1643

Handling dictionaries of variable length

I have a python script in which I have a function which returns a dictionary. The length of dictionary returned by the function is dynamic. For example two samples of dictionaries returned

sample 1

'ID': 'd1f1', 'counter': 1,'device_id': 35, 'equipment_id': 1, 20: 85.0, 14: 90.0, 43: 1, 34: 1

sample 2

'ID': 'd1f1', 'counter': 1,'device_id': 35, 'equipment_id': 1, 20: 85.0, 14: 90.0, 43: 1

In my python script I parse this dictionary and save these values in db.

code

ID = dict['device_id']
equipment = dict['equipment_id']
volts = dict[20]
power = dict[14]
health = dict[43]
status = dict[34]

in the second dictionary there is no value with key 34. So I want to save the status value as null. But if am assigning the values the way I am currently doing its throwing a key error. Can someone help me with how to handle this problem.

Thanks

Upvotes: 0

Views: 239

Answers (1)

adamkgray
adamkgray

Reputation: 1937

Seems like you want to return None if a dict does not contain a certain key. In this case you can use the get() function. It returns the value or None if the key does not exists. For example:

my_dict = {'a': 1}
a = my_dict.get('a')
b = my_dict.get('b')

In this case, the value of a will be 1, and the value of b will be None.

A more 'pythonic' solution is to use a try-except block, where you try to get the value, and return None when an exception is raised.

my_dict = {'a': 1}

try:
    b = my_dict['b']
except KeyError:
    b = None

Upvotes: 2

Related Questions