Skip to content
Advertisement

Get the key from a sub-dictionary and a value from a list of key-val pairs within it

I have a dictionary called metadata. It has a length of 2 keys, ‘status’ and ‘data’. I am only interested in the key ‘data’ and what lies within it. The subdictionary ‘data’ has 1,136 keys.

{'status': 'success',
 'data': {'async_tasks_count': [{'type': 'gauge',
    'help': 'Total number of async tasks spawned using spawn',
    'unit': ''}],
  'async_tasks_time_histogram': [{'type': 'histogram',
    'help': 'Time taken by async tasks',
    'unit': ''}],
  'attestation_production_cache_interaction_seconds': [{'type': 'histogram',
    'help': 'Time spent interacting with the attester cache',
    'unit': ''}],
  'attestation_production_cache_prime_seconds': [{'type': 'histogram',
    'help': 'Time spent loading a new state from the disk due to a cache miss',
    'unit': ''}]}

Within ‘data’ I need the Key and the Value of the 1st position (i.e. second elelment). For example the first Key within ‘data’ would be ‘async_tasks_count’ and the Value I need is ‘Total number of async tasks spawned using spawn’, the second Value.

It would be ideal to have them returned like:

(‘async_tasks_count’ : ‘Total number of async tasks spawned using spawn’, ‘async_tasks_time_histogram’ : ‘Time taken by async tasks’, ‘attestation_production_cache_interaction_seconds’: ‘Time spent interacting with the attester cache’, ‘attestation_production_cache_prime_seconds’: ‘Time spent loading a new state from the disk due to a cache miss’)

I’m using Python3

Advertisement

Answer

You can loop through data dictionary and then extract help property from each item.

The item is the dictionary with the data property.

result = {}
for key, value in metadata['data'].items():
    result[ key ] = value[0].get('help')
    
print(result) # for viewing the result
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement