简体   繁体   中英

How to pull out value from Key:Value Pair with Databricks Notebook

The following code recieves information from Service Bus and prints the information.

def myfunc():
    with ServiceBusClient.from_connection_string(CONNECTION_STR) as client:
        # max_wait_time specifies how long the receiver should wait with no incoming messages before stopping receipt.
        # Default is None; to receive forever.

          with client.get_queue_receiver(QUEUE_NAME, session_id=session_id, max_wait_time=3600) as receiver:
            for msg in receiver:
                # print("Received: " + str(msg))
                themsg = json.loads(str(msg))
                # complete the message so that the message is removed from the queue
                receiver.complete_message(msg)
                return themsg

I then assign a variable to the function as follows:

result = myfunc()

When I enter the following code

result['mappings']

I get the following output:

Out[45]: [{'ELLIPSE': {'method': 'ellipseItem',
   'tables': [{'database': 'foundation',
     'schema': 'AZ_FH_ELLIPSE',
     'table': 'ADS_FND_MSF620',
     'primaryKey': [{'column': 'DSTRCT_CODE', 'seqno': 1},
      {'column': 'WORK_ORDER', 'seqno': 2}]}],
   'columns': [{'column': 'D_WORK_ORDER_KEY',

I am now trying to extract 'AZ_FH_ELLIPSE' and 'ADS_FND_MSF620'

My attempt is as follows:

result['mappings']['table']

But I get the Typeerror:

TypeError: list indices must be integers or slices, not str

I'm aware this is simply piece of python code I should know, but any thoughts welcomed

The reason you're getting this error is because list always expects index with integers. Coming to the error - This error occurs because you have tried to access the dictionary using the key, when the dictionary is inside of a list. If you follow closely then key 'table' is within the dictionary 'ELLIPSE' and it exists at the first index position of the parent list.

Thereby, try accessing the dictionary keys as below -

result['mappings'][0]['ELLIPSE']['tables'][0]['schema']

Similarly,

result['mappings'][0]['ELLIPSE']['tables'][0]['table']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM