mathgeek
mathgeek

Reputation: 125

Is there an efficient way to retrieve values from dictionary

I have a dictionary of values. This is for a company name.

It has 3 keys:

{'html_attributions': [],
 'result' : {'Address': '123 Street', 'website' :'123street.com' 
 'status': 'Ok' }

I have a dataframe of many dictionaries. I want to loop through each row's dictionary and get the necessary information I want.

Currently I am writing for loops to retrieve these information. Is there a more efficient way to retrieve these information?

addresses = []
for i in range(len(testing)):
    try:
        addresses.append(testing['Results_dict'][i]['result']['Address'])
    except:
        addresses.append('No info')

What I have works perfectly fine. However I would like something that would be more efficient. Perhaps using the get() method? but I don't know how I can call to get the inside of 'result'.

Upvotes: 1

Views: 154

Answers (3)

Code Different
Code Different

Reputation: 93151

Try this:

def get_address(r):
    try:
        return r['result']['Address']
    except Exception:
        return 'No info'

addresses = df['Results_dict'].map(get_address)

This guards against cases where Result_dict is None, not a dict, or any key along the path way does not exist.

Upvotes: 1

Pooya Kamranjam
Pooya Kamranjam

Reputation: 435

This is a way faster solution if the data is big:

addresses = list(map(lambda x: x.get('result').get('Address', 'No info'), testing['Results_dict']))

Upvotes: 1

chandni goyal
chandni goyal

Reputation: 157

Here is how I deal with nested dict keys:

Example:

def keys_exists(element, *keys):
    if not isinstance(element, dict):
        raise AttributeError('keys_exists() expects dict as first argument.')
    if len(keys) == 0:
        raise AttributeError('keys_exists() expects at least two arguments, 
              one given.')

    _element = element
    for key in keys:
    try:
        _element = _element[key]
    except KeyError:
        return False
return True

For data :

{'html_attributions': [],
 'result' : {'Address': '123 Street', 'website' :'123street.com' 
 'status': 'Ok' }

if you want to check result exists or not use above function like this

`print 'result (exists/Not): {}'.format(keys_exists(data,"result"))` 

To check address exist inside result Try this

`print 'result > Address (exists/not): {}'.format(keys_exists(data, "result", "Address"))`

It will return output in True/False

Upvotes: 0

Related Questions